How to force one gesture to recognize before another using highPriorityGesture()
How to force one gesture to recognize before another using highPriorityGesture() 관련
Updated for Xcode 15
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")
}
}
}
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")
}
)
}
}
Using this alternative, “VStack tapped” will always be printed because the VStack
recognizer will always take priority over the circle's.