swiftui

SwiftUI - Respond to tap AND double tap with different actions


I need to respond to a single tap and double tap with different actions, but is SwiftUI the double tap gesture is interpreted as two single taps.

In swift you can use fail gesture, but no idea how to do it in SwiftUI.

Example:

.onTapGesture(count: 1) {
     print("Single Tap!")
}
.onTapGesture(count: 2) {
     print("Double Tap!")
}

TIA.


Solution

  • First one prevent second one to perform. So reverse the order of your code:

    .onTapGesture(count: 2) {
        print("Double Tap!")
    }
    .onTapGesture(count: 1) {
        print("Single Tap!")
    }
    

    Update: Second solution

    Since the above method reported not working in some situationis, you can try using gestures modifier instead:

    .gesture(TapGesture(count: 2).onEnded {
        print("double clicked")
    })
    .simultaneousGesture(TapGesture().onEnded {
        print("single clicked")
    })