Pass Parameter with UITapGestureRecognizer Pass Parameter with UITapGestureRecognizer xcode xcode

Pass Parameter with UITapGestureRecognizer


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.


For Swift 4

In Viewdidload

let label     =   UILabel(frame: CGRect(x: 0, y: h, width: Int(self.phoneNumberView.bounds.width), height: 30))                label.textColor = primaryColor                label.numberOfLines = 0                label.font = title3Font                label.lineBreakMode = .byWordWrapping                label.attributedText = fullString let phoneCall = MyTapGesture(target: self, action: #selector(self.openCall))        phoneCall.phoneNumber = "\(res)"            label.isUserInteractionEnabled = true            label.addGestureRecognizer(phoneCall)

Function as

@objc func openCall(sender : MyTapGesture) {        let number = sender.phoneNumber        print(number)}

Write Class as

class MyTapGesture: UITapGestureRecognizer {    var phoneNumber = String()}

Follow Step Properly and make change according to your variable , button ,label . It WORKS PROPERLY


The best way is to determind the parameter when the func imageTapped64is fired. You can get you params via the view (take a look to @Developer Sheldon answer) or in many other ways.