Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Using Gesture Priority in SwiftUI
Written by Team Kodeco

User interfaces often have to manage multiple types of user gestures. In SwiftUI, multiple gestures attached to the same view follow an order of priority—by default, the last gesture added gets the highest priority. But what if you need to customize this order? Enter SwiftUI’s gesture priority system.

Consider a scenario where you have an image view that can be manipulated with both drag and tap gestures. The challenge is to prioritize the drag gesture over the tap gesture. Here’s how to achieve this:

struct ContentView: View {
  @State private var position = CGSize.zero

  var body: some View {
    Image(systemName: "heart.fill")
      .font(.system(size: 100))
      .foregroundColor(.red)
      .padding()
      .offset(position)
      .gesture(
        DragGesture()
          .onChanged { gesture in
            self.position = gesture.translation
          }
          .onEnded { _ in
            print("Drag ended")
          }
          .simultaneously(with: TapGesture()
              .onEnded { _ in
                print("Inside Tapped")
              }
          )
      )
      .highPriorityGesture(
        TapGesture()
          .onEnded { _ in
            print("Tapped")
          }
      )
  }
}

Your preview should look like this:

SwiftUI provides modifiers to control the priority of gestures.
SwiftUI provides modifiers to control the priority of gestures.

In this example, a DragGesture is applied to the image view that allows you to move the image as you drag it around. Within the DragGesture, a TapGesture is also defined using the simultaneously modifier, printing “inside tapped” to the console when it’s recognized.

However, the magic happens with the highPriorityGesture modifier. This modifier is applied outside of the first gesture modifier block and introduces another TapGesture to the image. The tap gesture within the highPriorityGesture modifier is given higher priority than the one inside the DragGesture. Therefore, if you tap the image, “Tapped” is printed to the console instead of “Inside Tapped”.

The highPriorityGesture modifier gives you control over the hierarchy of gesture recognition, helping you create more sophisticated user interactions. By using it in combination with simultaneously(with:), you can design complex gesture interactions and precisely control how they should be recognized.

This gives you control over the user interaction, helping you create more sophisticated and nuanced interfaces with SwiftUI.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.