Skip to content

iOS Tap Gesture UITapGestureRecognizer

Platform Language License

UITapGestureRecognizer

Overview:

  1. Common class for Tap Gesture
  2. You can copy paste the view Extension class
  3. Swift 5.0 above
  4. Xcode 11 above
extension UIView {
    //MARK: addTapGesture
    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!()
        }
}
//MARK: MyTapGestureRecognizer Class
class MyTapGestureRecognizer: UITapGestureRecognizer {
    var action : (()->Void)? = nil
}

Now you can just call

anyView.addTapGesture {
    //tapGestureAction
    print("Gesture is working")
}

In above code anyView can be anyLabel, anyButton etc.,

Let's grow together 🌱

Cheers 🍻