Search code examples
swiftuilabeluitapgesturerecognizer

Swift - Multiple UILabel click events to same function


I need to add a UITapGestureRecognizer to multiple UILabel and they all need to go to the same function for handling.

What I have is this:

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

Recieved here:

@objc func myFunction(sender:UITapGestureRecognizer) { // Something... }

Working like a charm. Problem is that its only working with one UILabel (If adding addGestureRecognizer(tap) to multiple UIlabel it only works on the last one added)

So my question is:

How to achieve what I want to do here? Five different UILabels with tapRecognizer going to the same function


Solution

  • UIGestureRecognizer is to be used with a single view, you have to create a new instance of 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())