Search code examples
iosuitableviewswiftuigesturerecognizer

How to accelerate the identification of a single tap over a double tap?


I have a UITableView with row where I added single tap and double tap gestures:

let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:")
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
        
let singleTap = UITapGestureRecognizer(target: self, action: "singleTap:")
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
singleTap.requireGestureRecognizerToFail(doubleTap)

tableView.addGestureRecognizer(doubleTap)
tableView.addGestureRecognizer(singleTap)

Is there a way to reduce the time between when the first tap is made and when the gesture recognizer realize that it is a single tap and not a double tap?

I'm asking this because when I do a single tap, the new viewController appear quite late, giving a feeling that the app lags.


Solution

  • I found the answer on this link

    The swift version:

    class UIShortTapGestureRecognizer: UITapGestureRecognizer {
        let tapMaxDelay: Double = 0.3
    
        override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
            super.touchesBegan(touches, withEvent: event)
            delay(tapMaxDelay) {
                // Enough time has passed and the gesture was not recognized -> It has failed.
                if  self.state != UIGestureRecognizerState.Ended {
                    self.state = UIGestureRecognizerState.Failed
                }
            }
        }
    }
    

    With delay(delay: Double, closure:()->()):

    class func delay(delay:Double, closure:()->()) {
            dispatch_after(dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
        }