繁体   English   中英

如何以编程方式创建多个按钮和动作?

[英]How to create multiple buttons and action programmatically?

我正在使用 Swift 3.0。 我正在尝试生成按钮的动态网格如何以编程方式为每个生成的按钮提供唯一标识符

let button = UIButton(type: .system)
@IBOutlet weak var attendanceView: UIView!
override func viewDidLoad() {
    super.viewDidLoad()
    var xvalue = 8;
    var yvalue = 17;
    var button = UIButton();

    for _ in 0..<5{
        for _ in 0..<5{
        button = UIButton(frame: CGRect(x: xvalue, y: yvalue, width: 50 , height: 50))
        button.backgroundColor = .red()
        button.addTarget(attendanceView, action: #selector(buttonAction), for: .touchUpInside)
        self.attendanceView.addSubview(button)
        xvalue = xvalue + 72;
        }
        xvalue=8;
        yvalue = yvalue + 60;
    }
}

func buttonAction(sender: UIButton!) {
    button.backgroundColor = UIColor.green()
}

我已经走了这么远,但是当单击按钮时它崩溃了。

使用button.tag来区分按钮。 redUIColor的属性,所以你可以访问它UIColor.red 所以调整你的 for 循环

for i in 0..<5 {
    for i in 0..<5 {
        button = UIButton(frame: CGRect(x: xvalue, y: yvalue, width: 50 , height: 50))
        button.backgroundColor = .red
        button.addTarget(attendanceView, action: #selector(buttonAction), for: .touchUpInside)
        button.tag = i
        self.attendanceView.addSubview(button)         
    }
}

buttonAction()使用.tag

func buttonAction(sender: UIButton!) {
    switch (sender.tag){
    case 0:
        //button 0 action
    case 1:
        //button 1 action
    case 2:
        //button 2 action
    case 3:
        //button 3 action
    case 4:
        //button 4 action
    default:
        //default
    }
}

我的两分钱:我认为使用 so mocha 按钮会与不同的尺寸和设备发生冲突。 最好使用集合。 无论如何使用标签属性是正确的方法。 使用某种公式的 awn 很好,例如:

for r in 0..<10 {
    for c in 0..<20 {
        let tag = 1 + (r * 30) + c
    }
}

这样,您应该有不同的不重叠标签。

在回调中:

func buttonAction(sender: UIButton!) {
    let tag = sender.tag
    let row = tag % 30 // modulus...
    let col = tag - row * 30...
}

或类似。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM