我有一个数组,我想知道怎样才能在Swift 4中使用sender.tag
为4个UIButton添加标题
这是我的阵列:
let answer: array = ["Black","Green","Red","Gray"]
使用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
范围内。
导入UIKit
class 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)
}
}