0

What I am trying to achieve:

I am trying to execute two different tasks depending on if the user tapped the screen once or twice in the touchesBegan method.

In the process of doing so, I am delaying the execution of the singleTapTask by 0.3s to be able to cancel the DispatchWorkItem belonging to the doubleTapTask.


My approach:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {

        let singleTapTask = DispatchWorkItem {
            // single tap
        }
        let doubleTapTask = DispatchWorkItem {
            // double tap
        }

        if touch.tapCount == 1 {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: singleTapTask)

        } else if touch.tapCount == 2 {
            singleTapTask.cancel()
            DispatchQueue.main.async(execute: doubleTapTask)

        }
    }
}

Issue:

For some reason the singleTapTask is still executed alongside with the doubleTapTask even though the singleTapTask has been canceled. I can not figure out why the singleTapTask is executed in the first place and would highly appreciate your help :)

Devapploper
  • 6,062
  • 3
  • 20
  • 41
  • Why are you not using UIGestureTapRecognizer for this? – Nikita Gaidukov Jul 25 '17 at 19:52
  • I thought about wanting only a certain part of the screen to be eligible for the single/double touch recognition but I might end up doing so @NikitaGaydukov – Devapploper Jul 25 '17 at 20:13
  • take a look at this answer: https://stackoverflow.com/questions/9346315/uigesturerecognizer-for-part-of-a-uiview. It will help you restrict the tappable area. – Nikita Gaidukov Jul 26 '17 at 06:48

1 Answers1

2

A simple approach for this would be to add 2 UITapGestureRecognizer to your view (singleTapGestureRecognizer and doubleTapGestureRecognizer).

The first one configured with singleTapGestureRecognizer.numberOfTapsRequired = 1, the second one with doubleTapGestureRecognizer.numberOfTapsRequired = 2.

Now add singleTapGestureRecognizer.require(toFail: singleTapGestureRecognizer)

Furthermore, with your approach above you are not targeting sequential single and double taps, but the number of taps at one tap (number of fingers tapping at the same time)

mschwarz
  • 1,407
  • 1
  • 10
  • 7