Swift - 多个 UILabel 单击事件到相同的功能

Sou*_*y86 1 uilabel uitapgesturerecognizer swift

我需要将 a 添加UITapGestureRecognizer到多个,UILabel并且它们都需要转到相同的函数进行处理。

我有的是这个:

@IBOutlet weak var label_something: UILabel!
let tap = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
label_something.addGestureRecognizer(tap)
Run Code Online (Sandbox Code Playgroud)

在这里收到:

@objc func myFunction(sender:UITapGestureRecognizer) { // Something... }
Run Code Online (Sandbox Code Playgroud)

像魅力一样工作。问题是它只适用于一个 UILabel(如果添加addGestureRecognizer(tap)到多个UIlabel它只适用于添加的最后一个)

所以我的问题是:

如何实现我想在这里做的事情?带有 tapRecognizer 的五个不同的 UILabels 具有相同的功能

a.m*_*sri 5

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())
Run Code Online (Sandbox Code Playgroud)