SwiftUI - Multiple views react simultaneously to gesture?

262 views Asked by At

I am attempting to allow one tap gesture to trigger different views that are in a ZStack. When I tap on the red square that is superimposed on the yellow square, I would like both to react to the touch.

So if I tap on the red square, I should receive the printout "Red rectangle tapped" and "Yellow rectangle tapped". And not only "Red rectangle tapped".

Is there any easy way to do this?

struct MultiTouchView: View {
    var body: some View {
        ZStack(alignment: .center) {
            Rectangle()
                .foregroundColor(.yellow).opacity(0.3)
                .onTapGesture {
                    print("Yellow rectangle tapped")
                }
            
            Rectangle()
                .foregroundColor(.red)
                .frame(width: 200, height: 200)
                .onTapGesture {
                    print("Red rectangle tapped") // -> I would like this tap to react but also to allow the yellow rectangle to react to the same tap
                }
        }
    }
}
1

There are 1 answers

5
Bezaleel On

Add a single tap gesture to the ZStack instead. That should handle any event you want to occur on tapping both red and yellow rectangles

struct MultiTouchView: View {
var body: some View {
    ZStack(alignment: .center) {
                Rectangle()
                    .foregroundColor(.yellow).opacity(0.3)
                    .onTapGesture {
                        print("Yellow rectangle tapped")
                    }
                
                Rectangle()
                    .foregroundColor(.red)
                    .frame(width: 200, height: 200)
                    .onTapGesture {
                        print("Red rectangle tapped") // -> I would like this tap to react but also to allow the yellow rectangle to react to the same tap
                    }.simultaneousGesture(
                        TapGesture()
                            .onEnded { _ in
                                print("Yellow rectangle tapped")// outer simultaneous tap
                            }
                    )
            }

} }