iosswiftuitapgesturerecognizer

Pass Parameter with UITapGestureRecognizer


Is there any way i can pass parameters with UITapGestureRecognizer? I've seen this answered for objective-c but couldn't find an answer for swift

test.userInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped4:"))
// Something like text.myParamater
test.addGestureRecognizer(tapRecognizer)

And then receive myParameter under func imageTapped4(){}


Solution

  • One approach would be to subclass UITapGestureRecognizer and then set a property, I've posted an example below. You could also do some check on the sender and check if equal to some tag, class, string, e.t.c

    class ViewController: UIViewController {
    
        @IBOutlet weak var label1: UILabel!
        @IBOutlet weak var image: UIImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            image.userInteractionEnabled = true;
            let tappy = MyTapGesture(target: self, action: #selector(self.tapped(_:)))
            image.addGestureRecognizer(tappy)
            tappy.title = "val"
        }
    
        func tapped(sender : MyTapGesture) {
            print(sender.title)
            label1.text = sender.title
        }
    }
    
    class MyTapGesture: UITapGestureRecognizer {
        var title = String()
    }
    

    There are lots of examples on SO, have a look, good luck.