ios - 以编程方式循环 UIButton

标签 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 个按钮!

最佳答案

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)

        }
}

关于ios - 以编程方式循环 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544923/

相关文章:

ios - 将事件的 RecurrenceRule 保存到 CoreData

IOS:将图像添加到自定义 MKAnnotationview

android - Rails protect_from_forgery 与移动应用程序

ios - 获取请求返回 {(//value )} 而不仅仅是值

iphone - 根据选择更改 UITableViewCell 中按钮的背景颜色

ios - Swift:为不同的选项卡设置不同的导航栏按钮

swift - 未找到 UITableView 原型(prototype)单元格

ios - 如何显示所有页面导航栏按钮

ios - 如何设置 UIButton 背景颜色的 alpha?

ios - awakeFromNib 与 drawRect 中的 CALayer