我需要向多个UITapGestureRecognizer
添加UILabel
,他们都需要转到同一个函数进行处理。
我拥有的是:
@IBOutlet weak var label_something: UILabel!
let tap = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
label_something.addGestureRecognizer(tap)
在这里收到:
@objc func myFunction(sender:UITapGestureRecognizer) { // Something... }
像魅力一样工作。问题是它只使用一个UILabel(如果将addGestureRecognizer(tap)
添加到多个UIlabel
,它只适用于添加的最后一个)
所以我的问题是:
如何实现我想在这里做的事情?五个不同的UILabel与tapRecognizer具有相同的功能
答案 0 :(得分:4)
UIGestureRecognizer
将与单个视图一起使用,您必须创建UIGestureRecognizer
的新实例
func setGesture() -> UITapGestureRecognizer {
var myRecognizer = UITapGestureRecognizer()
myRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
return myRecognizer
}
label_something1.addGestureRecognizer(setGesture())
label_something2.addGestureRecognizer(setGesture())
答案 1 :(得分:2)
如果您从UITapGestureRecognizer添加新实例,它将正常工作,例如
let tap = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
label_1.addGestureRecognizer(tap)
let tap2 = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
label_2.addGestureRecognizer(tap)
答案 2 :(得分:0)
每个UIView都需要自己的识别器,我有一个小帮手功能。随意复制/粘贴。
react-router