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

标签 ios swift uibutton swift3

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

关于ios - 如何以编程方式创建多个按钮和操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534545/

相关文章:

php - 苹果推送 PHP : No all notifications received

ios - 如何创建谓词来获取同一属性的所有不重复结果的实体?

VisionKit 框架 iOS 13 中的 iOS 应用程序崩溃

swift - 在拍摄照片之前切换 AVCaptureSessionPreset

swift - 如何修复带有无效签名的dylib?

ios - UIButtons 在动画期间没有响应 - iOS Swift 3

ios - 用google direction api绘制路径

ios - 宽度的 CALayer 动画

ios - 自定义 UIButton Swift 2.0

iphone - 如何在圆形矩形按钮中添加箭头图标