0

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!

jeep
  • 615
  • 2
  • 10
  • 19

1 Answers1

1

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
                }
        )
    }
}
ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • Thank you!This works!But it failed when i put it in my complicated nested views. Some views underneath can not receive the tap event while some do receive. – jeep May 10 '23 at 11:49