以编程方式循环UIButton

时间:2017-06-14 12:32:53

标签: ios swift uibutton

我正在创建按钮,我想要循环14次,2行,每行有7个按钮,每个按钮之间有一点空间,我该怎么做?

这是我的代码:

var tileButton = UIButton()
func createButton() {

            for i in 0...13 {

                tileButton.frame = CGRect(x: 20, y: 530, width: 50, height: 50)
                tileButton.layer.masksToBounds = true
                tileButton.layer.cornerRadius = 15
                tileButton.setImage( UIImage.init(named: "cell"), for: .normal)
                tileButton.addTarget(self, action: "tileButton", for: UIControlEvents.touchUpInside)
                tileButton.setTitle("\(String(i))", for: .normal)
                view.addSubview(tileButton)

            }
    }

当我运行时,此代码只显示1个按钮!

2 个答案:

答案 0 :(得分:0)

let BUTTON_PADDING: CGFloat = 10
func createButton() {

        for i in 0...13 {
            let y: CGFloat = i < 7 ? 530 : 600

            let tileButton = UIButton(frame: .zero)

            tileButton.frame = CGRect(x: (50*i) + BUTTON_PADDING, y: y, width: 50, height: 50)
            tileButton.layer.masksToBounds = true
            tileButton.layer.cornerRadius = 15
            tileButton.setImage( UIImage.init(named: "cell"), for: .normal)
            tileButton.addTarget(self, action: "tileButton", for: UIControlEvents.touchUpInside)
            tileButton.setTitle("\(String(i))", for: .normal)
            view.addSubview(tileButton)

        }
}

答案 1 :(得分:0)

这是最准确的解决方案:

let buttonWidth = self.view.frame.size.width / 7
var xAxis : CGFloat = 10

        for i in 0...6 {

            let letterButton = UIButton()

            letterButton.frame = CGRect(x: xAxis , y: self.view.frame.size.height - (buttonWidth * 2) - 20, width: buttonWidth, height: buttonWidth)

            letterButton.layer.masksToBounds = true
            letterButton.layer.cornerRadius = 15
            letterButton.setImage(UIImage.init(named: "cell"), for: .normal)

            let letterButton2 = UIButton()

            letterButton2.frame = CGRect(x: xAxis, y: self.view.frame.size.height - buttonWidth - 20, width: buttonWidth, height: buttonWidth)

            letterButton2.layer.masksToBounds = true
            letterButton2.layer.cornerRadius = 15
            letterButton2.setImage(UIImage.init(named: "cell"), for: .normal)

            xAxis = xAxis + buttonWidth

            view.addSubview(letterButton)
            view.addSubview(letterButton2)

        }