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 = true
self.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 = true
self.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
Just a note - Don't forget to enabled interaction on the view:
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
view.addGestureRecognizer(tap)
// view.userInteractionEnabled = true
self.view.addSubview(view)
Implementing tap gesture
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "touchHappen")
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)
Calls this function when the tap is recognized.
func touchHappen() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
self.view.endEditing(true)
}
Update for For Swift 3 +
let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchHappen(_:)))
yourView.addGestureRecognizer(tap)
yourView.userInteractionEnabled = true
func touchHappen(_ sender: UITapGestureRecognizer) {
print("Hello Dear you are here")
}