'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 1:[1]
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")
})
Solution 2:[2]
You can also setup a count for TapGesture like so:
.simultaneousGesture(TapGesture(count: 2).onEnded {
// double tap logic
})
Per Apple Developer Documentation: https://developer.apple.com/documentation/swiftui/tapgesture
Solution 3:[3]
Text("Tap Me!").gesture(
TapGesture(count: 2)
.onEnded({ print("Tapped Twice!”)})
.exclusively(before:
TapGesture()
.onEnded({print("Tapped Once!”) })
)
)
Solution 4:[4]
There does not seem to be a simple solution (yet), most of these answers trigger both actions. The workaround I have discovered feels clumsy, but works smoothly:
struct hwsView: View {
var body: some View {
VStack {
Text("HWS")
.onTapGesture {
print("Text single tapped")
}
}
.highPriorityGesture(
TapGesture(count: 2)
.onEnded { _ in
print("hws double tapped")
}
)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ebey Tech |
| Solution 3 | user1192887 |
| Solution 4 | geoffry |
