< How to read tap and double-tap gestures | How to make two gestures recognize at the same time using simultaneousGesture() > |
Updated for Xcode 14.2
If you have one SwiftUI view inside another, and both have the same gesture recognizer, the system will always trigger the recognizer on the child before the parent. You can change this behavior by using highPriorityGesture()
, which will force the system to prioritize one gesture over another.
For example, we could write some code to place a circle inside a VStack
, giving both a simple tap gesture action. In this situation the circle’s gesture action will always be triggered:
struct ContentView: View {
var body: some View {
VStack {
Circle()
.fill(.red)
.frame(width: 200, height: 200)
.onTapGesture {
print("Circle tapped")
}
}
.onTapGesture {
print("VStack tapped")
}
}
}
Download this as an Xcode project
If you want the VStack
gesture to be triggered in place of the circle’s, you need to replace the onTapGesture()
modifier with highPriorityGesture()
like this:
struct ContentView: View {
var body: some View {
VStack {
Circle()
.fill(.red)
.frame(width: 200, height: 200)
.onTapGesture {
print("Circle tapped")
}
}
.highPriorityGesture(
TapGesture()
.onEnded { _ in
print("VStack tapped")
}
)
}
}
Download this as an Xcode project
Using this alternative, “VStack tapped” will always be printed because the VStack
recognizer will always take priority over the circle’s.
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.