2

I found some good code on another stack overflow question for this, however my single tap code is running when I do a single tap or a double tap. heres the code (by the way, double tap meaning I tap once, and within 0.3 seconds I tap again, not 2 fingers simultaneously tapping)

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        let touch: AnyObject? = touches.anyObject()
        if (touch?.tapCount == 2) {
            NSObject.cancelPreviousPerformRequestsWithTarget(self)
        }
    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        let touch: AnyObject? = touches.anyObject()
        if (touch?.tapCount == 1) {
            let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC)))
            dispatch_after(dispatchTime, dispatch_get_main_queue(), {
                println("this runs only if single tap")
            })
        } else if (touch?.tapCount == 2) {
            println("double tap touches ended")

        }
    }

I thought that the NSObject.cancelPreviousPerformRequestsWithTarget(self) is supposed to stop the single tap block from running, however my println("this runs only if single tap") is still running when I double tap. First my double tap runs, then after 0.3 seconds the single tap code runs too.. any ideas on what I'm doing wrong?

Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

2 Answers2

0

the problem was that

NSObject.cancelPreviousPerformRequestsWithTarget(self)

does not cancel a

dispatch_after(dispatchTime, dispatch_get_main_queue()

therefore this will never work. See my other question for further details about this

Community
  • 1
  • 1
Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127
0

I found the same problem. Finally this code works right for me:

var isDoubleTap = false
let timeToWaitAsecondTap: TimeInterval = 0.2  // Whatever you need

func singleTapAction() {
    if isDoubleTap {
        return
    }
    print(#function)
}

func doubleTapAction() {
    print(#function)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else {
        return
    }
    if touch.tapCount == 1 {
        DispatchQueue.main.asyncAfter(deadline: .now() + timeToWaitAsecondTap) {
            self.singleTapAction()    // always execute
            self.isDoubleTap = false  // always execute
        }
    } else if touch.tapCount == 2 {
        isDoubleTap = true  // not-always execute
        doubleTapAction()   // not-always execute
    }
}
Miguel Gallego
  • 427
  • 4
  • 7