Swift - How to identify difference between single and double taps

1.8k Views Asked by At

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
2

There are 2 best solutions below

0
Lamour On BEST ANSWER

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) 
0
Mozahler On

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)