Search This Blog

Monday, October 30, 2017

iOS Swift. How to detect double OR triple tap with UITapGestureRecognizer

For detecting touches in iOS application we use UITapGestureRecognizer. When we need react only on special number of touches, for example two or three, we must simply specify this parameter for gesture recognizer object.

When number of touches is 3
let tapGestureRecognizer = UITapGestureRecognizer(target: self,
                                                          action: #selector(imageTappedTriple))
tapGestureRecognizer.numberOfTapsRequired = 3

When number of touches is 2
let tapGestureRecognizer = UITapGestureRecognizer(target: self,
                                                          action: #selector(imageTappedDouble))
tapGestureRecognizer.numberOfTapsRequired = 2

Important to remember is make enable image for interaction with user.
self.imageView.isUserInteractionEnabled = true

Full code.
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGestureRecognizer = UITapGestureRecognizer(target: self,
                                                          action: #selector(imageTappedTriple))
        tapGestureRecognizer.numberOfTapsRequired = 3
        self.imageView.isUserInteractionEnabled = true
        self.imageView.addGestureRecognizer(tapGestureRecognizer)
    }
    
    @objc func imageTappedTriple(sender: UITapGestureRecognizer) {
        print("Image was tapped three times!")
    }

}

5 comments:

  1. You have shared a very informative Article. I was looking for this kind of unique information. Please share more related information so I can get more knowledge.
    -Custom Web Design and Development

    ReplyDelete
  2. There are many articles circulating on internet that exaggerate about Custom Designed Websites. But your article is an exception that made me understand it without any difficulty.

    ReplyDelete
  3. This is an excellent article! Thank you a lot. I'm in desperate need of these suggestions. The in-depth explanation is quite beneficial. It was incredibly encouraging to see how you write. Best Custom Websites

    ReplyDelete
  4. Thank you Sir, you made it easy as pie. Now i am able to understand and have enough knowledge about this. It is only because of you.
    Custom Designed Websites

    ReplyDelete
  5. Amazing write-up! The blog was very informative. Keep it up!
    Software Testing Services

    ReplyDelete