I have a UIView and and I have added tap gesture to it:
let tap = UITapGestureRecognizer(target: self, action: Selector(\"handleTap:\"))
tap.delegate = self
I wanted to specify two points which kept causing me problems.
This is how it works in Swift 3:
@IBOutlet var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap))
myView.addGestureRecognizer(tap)
}
func handleTap() {
print("tapped")
}
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
let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
frontView.addGestureRecognizer(tap)
// Make sure this is not private
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
}
try the following extension
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
and then use it :
submitBtn.addTapGesture {
//your code
}
you can even use it for cell
cell.addTapGesture {
//your code
}
Swift 4
First, create an object of UITapGestureRecognizer
var tapGesture = UITapGestureRecognizer()
The second step is to initialise UITapGestureReconizer. Enable the user interaction, then add it.
override func viewDidLoad() {
super.viewDidLoad()
tapGesture = UITapGestureRecognizer(target: self, action: #selector(YourViewController.myviewTapped(_:)))
infosView.isUserInteractionEnabled = true
infosView.addGestureRecognizer(tapGesture)
view.addSubview(infosView)
}
Third, create a method
@objc func myviewTapped(_ recognizer: UIGestureRecognizer) {
print("button is tapped")
}