我正在使用 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
来区分按钮。 red
是 UIColor
的属性,因此您可以访问它 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/