Andy
Andy

Reputation: 179

Swift - How to identify difference between single and double taps

I know that there are posts out there that solves the identifying difference between single and double taps problem but they are all either outdated or in c++. So, I want to know how to identify the difference between single and double taps because every time I double tap the system thinks it is a tap. I did set the value of the numberOfTaps to 1 for single tap and 2 for double tap.

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(respondToTapGesture(gesture:)))
    view.addGestureRecognizer(tap)

    tap.numberOfTapsRequired = 1

let doubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(respontToDoubleTapGesture(gesture:)))
    view.addGestureRecognizer(doubleTap)

    doubleTap.numberOfTapsRequired = 2

Upvotes: 3

Views: 1901

Answers (2)

Mozahler
Mozahler

Reputation: 5303

The problem is that you have two different recognizers which are trying to recognize the gesture.

This code will allow each of them to work:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

You need to make sure you've declared the controller as a gesture recognition delegate:

class FromDB: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
}

you also need to require the single tap to fail for the double tap to kick in:

tap.require(toFail: doubleTap)

Upvotes: 1

Lamour
Lamour

Reputation: 3030

In order to recognize the taken action or to differentiate between the single tap and double, you need to fail the gesture, just add that code below

tap.require(toFail: doubleTap) 

Upvotes: 9

Related Questions