Skip to main content

How to force one gesture to recognize before another using highPriorityGesture()

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to force one gesture to recognize before another using highPriorityGesture() 관련

SwiftUI by Example

Back to Home

How to force one gesture to recognize before another using highPriorityGesture() | SwiftUI by Example

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")
        }
    }
}

Download this as an Xcode projectopen in new window

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 projectopen in new window

Using this alternative, “VStack tapped” will always be printed because the VStack recognizer will always take priority over the circle's.

Similar solutions…
How to create gesture chains using sequenced(before:) | SwiftUI by Example

How to create gesture chains using sequenced(before:)
How to make two gestures recognize at the same time using simultaneousGesture() | SwiftUI by Example

How to make two gestures recognize at the same time using simultaneousGesture()
How to add a gesture recognizer to a view | SwiftUI by Example

How to add a gesture recognizer to a view
How to force views to one side inside a stack using Spacer | SwiftUI by Example

How to force views to one side inside a stack using Spacer
How to mask one view with another | SwiftUI by Example

How to mask one view with another

이찬희 (MarkiiimarK)
Never Stop Learning.