我有一个数组,我想知道如何在Swift 4中使用sender.tag
向4个UIButton添加标题
这是我的数组:
let answer: array = ["Black","Green","Red","Gray"]
答案 0 :(得分:0)
使用sender.tag
作为answer
数组的索引。使用guard
确保sender.tag
是有效的索引(这样就不会崩溃):
let answer = ["Black", "Green", "Red", "Gray"]
@IBAction func buttonPressed(_ sender: UIButton) {
guard answer.indices.contains(sender.tag) else { return }
sender.setTitle(answer[sender.tag], for: .normal)
}
如果将按钮连接到此@IBAction
,并设置tag
值0
至3
,则当按钮位于按下。
如果您的按钮属于插座系列:
@IBOutlet var buttons: [UIButton]!
您可以这样设置它们(例如,在viewDidLoad()
中)
buttons.forEach { $0.setTitle(answer[$0.tag], for: .normal)
同样,请确保将tag
的值设置在answer.indices
范围内。
答案 1 :(得分:0)
导入UIKit
ViewController类:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let array = ["Black","Green","Red","Gray"]
var oldButton = UIButton()
for i in 1...array.count {
let button = UIButton()
if i == 1 {
button.frame = CGRect(x: 10, y: 40, width: 90, height: 20)
button.tag = i
button.addTarget(self, action: #selector(ViewController.selctorButton(_:)), for: UIControl.Event.touchDown)
button.setTitle(array[button.tag - 1], for: .normal)
}
else {
button.frame = CGRect(x: oldButton.frame.maxX + 10, y: 40, width: 90, height: 20)
button.tag = i
button.addTarget(self, action: #selector(ViewController.selctorButton(_:)), for: UIControl.Event.touchDown)
button.setTitle(array[button.tag - 1], for: .normal)
}
button.backgroundColor = UIColor.black
view.addSubview(button)
oldButton = button
}
}
@objc func selctorButton(_ sender : UIButton){
print(sender.tag)
}
}