Swift 3 - 为循环UIButtons创建

时间:2017-07-15 10:00:54

标签: for-loop swift3 uibutton

大家好,我在for循环中创建了14个按钮,但在一个变量中每个7个按钮例如:

for i in 0...6 {
    var button = UIButton()
    ...
    var button2 = UIButton()
    ...
}

但我想在一个变量中创建14个按钮,如图所示为for循环:

enter image description here

在图片中我使用两个按钮进行循环

我的尺码,xAxis和yAx必须是:

let buttonWidth = self.view.frame.size.width / 7
var xAxis : CGFloat = 1
let yAxis : CGFloat = self.view.frame.size.height - (tileWidth * 2) - 100
let yAxis2 : CGFloat = self.view.frame.size.height - (tileWidth + 100)

那么如何使用相同大小和轴的for循环创建14个按钮?像这样:

for i in 0...13 {

    var button = UIButton()
    ...

}

1 个答案:

答案 0 :(得分:1)

修改

    let emptySpace:CGFloat = 40 //how much you want (left + right)
    var xAxis:CGFloat = emptySpace/2
    let space:CGFloat = 2
    let buttonWidth = ((self.view.frame.size.width)-((space*7)+emptySpace)) / 7

    var yAxis : CGFloat = self.view.frame.size.height - (tileWidth * 2) - 100
    let yAxis2 : CGFloat = self.view.frame.size.height - (tileWidth + 100)
    for i in 1...14 {

        let button = UIButton(type: .roundedRect)
        button.frame = CGRect(x: xAxis, y: yAxis, width: buttonWidth, height: buttonWidth)
        button.layer.cornerRadius = 10
        xAxis = xAxis+buttonWidth+space
        button.backgroundColor = UIColor.orange
        view.addSubview(button)


        if i%7 == 0 {
            xAxis = emptySpace/2
            yAxis = yAxis2+space
        }

    }