【问题标题】:How to create multiple buttons and action programmatically?如何以编程方式创建多个按钮和操作?
【发布时间】:2016-09-16 14:57:30
【问题描述】:

我正在使用 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()
}

我走了这么远,但点击按钮时它崩溃了。

【问题讨论】:

  • 请,当您发布有关崩溃的问题时,您必须包含崩溃中完整且准确的错误消息,并指出导致崩溃的确切代码行。
  • 把_改成i,然后加上button.tag = i。但是你的头衔和你说发生车祸有什么关系?这里的实际问题是什么?

标签: ios swift uibutton swift3


【解决方案1】:

使用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
    }
}

【讨论】:

  • 这与未知崩溃有什么关系? i 是什么?
  • OP' 代码甚至没有编译,什么崩溃是未知的? i 我猜是按钮的 ID
  • 阅读问题的最后一行(代码下方)。
  • 如果这段代码正在编译,这意味着它实际上不是 Swift 3
【解决方案2】:

我的两分钱:我认为使用 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...
}

或类似的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多