How to enable multiple gesture simultaneously in SwiftUI

In this tutorial, we will see how to recognize two gestures simultaneously in SwiftUI.

SwiftUI normally only activates one gesture recognizer action at a time, and it prioritizes the view at the top of our view hierarchy.

Now, if we want multiple gestures to be recognized simultaneously, we can use the simultaneousGesture(). This is a container event handler, which can recognize two child gestures at the same time.

Set up SwiftUI View

First of all, I will set up a SwiftUI view where I want the gestures to be recognized. Here I will create a VStack and within the VStack I will create a rounded rectangle.

Then I will apply the onTapGesture to both of them and see how it will work.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: 20)
                .fill(.mint)
                .frame(width: 100, height: 200)
                .onTapGesture {
                    print("Rectangle Tapped")
                }
        }
        .onTapGesture {
            print("VStack Tapped")
        }
    }
}

Output:

 

How to enable multiple gesture simultaneously in SwiftUI

As you can see in the above output, only one tap gesture is recognized at a time. But we want those two gestures to be recognized simultaneously. Now, follow the approach below to achieve this.

Implement simultaneousGesture()

To make both gestures recognize simultaneously, I will add the simultaneousGesture() modifier to the parent view, which is the VStack in this case. Then I will use the TapGesture() within it.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: 20)
                .fill(.mint)
                .frame(width: 200, height: 100)
                .onTapGesture {
                    print("Rectangle Tapped")
                }
        }
        .simultaneousGesture(
            TapGesture()
                .onEnded { _ in
                    print("VStack Tapped")
                }
        )
    }
}

Now, with this modification, both gestures will be recognized simultaneously.

Output:

How to enable multiple gesture simultaneously in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *