override func viewDidLoad() {
super.viewDidLoad()
for i in 1...10 {
//设置UILabel的属性
let label = UILabel()
label.frame = CGRect(x: 10, y: i * 40, width: 200, height: 25)
label.tag = i
label.text = "这是第\(i)个UILabel"
label.isUserInteractionEnabled = true
view.addSubview(label)
//添加手势
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(ViewController.userClick(sender:)))
label.addGestureRecognizer(tapGesture)
}
}
@objc private func userClick(sender: UITapGestureRecognizer) {
print(sender.description)
}
1.1 通过打印sender的属性,输出的内容如下:
1.2 通过打印我们发现UITapGestureRecognizer这个类有一个view属性是UILabel类型,因此我们可以确定通过sender.view!.tag就能拿到点击的是哪个UILabel,最终代码如下:
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...10 {
//设置UILabel的属性
let label = UILabel()
label.frame = CGRect(x: 10, y: i * 40, width: 200, height: 25)
label.tag = i
label.text = "这是第\(i)个UILabel"
label.isUserInteractionEnabled = true
view.addSubview(label)
//添加手势
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(ViewController.userClick(sender:)))
label.addGestureRecognizer(tapGesture)
}
}
@objc private func userClick(sender: UITapGestureRecognizer) {
let myLabel = view.viewWithTag(sender.view!.tag) as! UILabel
print(myLabel.text ?? "")
}
这是第6个UILabel
这是第4个UILabel
这是第4个UILabel
这是第3个UILabel
这是第1个UILabel