How to call gesture tap on UIView programmatically in swift How to call gesture tap on UIView programmatically in swift swift swift

How to call gesture tap on UIView programmatically in swift


You need to initialize UITapGestureRecognizer with a target and action, like so:

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))myView.addGestureRecognizer(tap)

Then, you should implement the handler, which will be called each time when a tap event occurs:

@objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {    // handling code}

So now calling your tap gesture recognizer event handler is as easy as calling a method:

handleTap()


For anyone who is looking for Swift 3 solution

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))view.addGestureRecognizer(tap)view.isUserInteractionEnabled = trueself.view.addSubview(view)// function which is triggered when handleTap is called@objc func handleTap(_ sender: UITapGestureRecognizer) {     print("Hello World")  }


For Swift 4:

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))view.addGestureRecognizer(tap)view.isUserInteractionEnabled = trueself.view.addSubview(view)// function which is triggered when handleTap is called@objc func handleTap(_ sender: UITapGestureRecognizer) {    print("Hello World")}

In Swift 4, you need to explicitly indicate that the triggered function is callable from Objective-C, so you need to add @objc too your handleTap function.

See @Ali Beadle 's answer here: Swift 4 add gesture: override vs @objc