How to call gesture tap on UIView programmatically in swift

George picture George · Feb 23, 2015 · Viewed 288.9k times · Source

I have a UIView and and I have added tap gesture to it:

let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
tap.delegate = self
myView.addGesture(tap)

I am trying to call it programmatically in the testfile.

sendActionForEvent

I am using this function, but it is not working:

myView.sendActionForEvent(UIEvents.touchUpDown)

It shows unrecognised selector sent to instance.

How can I solve this problem?

Answer

Salavat Khanov picture Salavat Khanov · Feb 23, 2015

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()