Tapping overlapping views and triggering both onTapGesture of them.(Tapping through) in SWIFTUI

320 Views Asked by At

I have two overlapping views inside a ZStack. When I tap the top view, it triggers its onTapGesture first and then triggers the onTapGesture of the view underneath. Does any one know how to achieve this? Any help would be much appreciated!

1

There are 1 best solutions below

1
ChrisR On

You can use simultaneousGesture, e.g. like this:

struct ContentView: View {
    var body: some View {
        ZStack {
            Text("Tap Me 1")
                .frame(width: 200, height: 200)
                .background(.green)
                .cornerRadius(10)
                .padding(.top, 100)

            Text("Tap Me 2")
                .padding()
                .background(.red)
                .cornerRadius(10)
            
                .onTapGesture {
                    print("2 tapped") // inner tap
                }
        }
        .simultaneousGesture(
            TapGesture()
                .onEnded { _ in
                    print("1 tapped") // outer simultaneous tap
                }
        )
    }
}