在字母数上动态创建UIView

时间:2015-12-04 13:06:14

标签: ios swift uiview swift2

我已经创建了关于字母数量的视图,但我想创建像我的句子(Power fade)前五个视图和包含空格之间的四个视图

enter image description here

这是我的代码..

for(i=0; i<strFinal?.characters.count; i++) {

        ansview = UIView(frame: CGRectMake(viewwidth-5, 10, 30, 30))
        ansview.layer.cornerRadius = 0.2 * btn.bounds.size.width
        ansview.backgroundColor = UIColor.grayColor()
        viewAnswer.addSubview(ansview)
        viewwidth = viewwidth + 35
 }

提前致谢...

1 个答案:

答案 0 :(得分:0)

好的,我为您准备了一些剪切代码,只需要您创建名为ViewController的临时视图控制器并粘贴下面列出的代码:

    import UIKit

class ViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        let strFinal = "go man!"
        let commonSpacing = CGFloat(5)
        let spaceSpacing = CGFloat(30)

        var viewOffset = CGFloat(0)
        for(var i = 0; i < strFinal.characters.count ; i++) {

            let charView = UIView(frame: CGRectMake(viewOffset, 10, 30, 30))
            charView.backgroundColor = UIColor.grayColor()
            view.addSubview(charView)

            let currCharacter = strFinal[i]

            var tempSpacing = commonSpacing
            if currCharacter == " " {
                tempSpacing = spaceSpacing
            }

            viewOffset = charView.frame.maxX + tempSpacing
        }
    }

}

extension String {

    subscript (i: Int) -> Character {
        return self[self.startIndex.advancedBy(i)]
    }
}

我希望这对你提出的详细问题不是很好的答案

现在您可以根据自己的目的自定义此代码。