3

I've been trying to use .onTapGesture to detect if the user taps on the screen. However, I noticed that it doesn't get triggered if the user taps on actionable elements like buttons and pickers. Is there a way to detect if the user taps on the screen, including these actionable elements without having to manually call my viewTapped function for each button, picker, etc. separately?

Here's the code I used to test this.

struct ContentView: View {
    @State var mode = 0
        
    var body: some View {
        ZStack {
            VStack {
                Text("Hello, world!")
                    .padding()
                
                Picker(
                    selection: $mode,
                    label: Text("Picker")) {
                    Text("Option 1").tag(0)
                    Text("Option 2").tag(1)
                }
                .pickerStyle(SegmentedPickerStyle())
                .frame(width: 200)
                .foregroundColor(.white)
                .padding()
                
                Button {
                    print("button clicked")
                } label: {
                    Text("Click me")
                }
                .padding()
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.green)
        .onTapGesture {
            viewTapped()
        }
    }
    
    public func viewTapped() {
        print("view tapped")
    }
}
1
  • So you want both button clicked and view tapped printed? Commented Jul 8, 2021 at 22:46

1 Answer 1

2

If you need to detect touches simultaneity, you need the simultaneousGesture modifier instead. like:


.simultaneousGesture(
    TapGesture()
        .onEnded {
            viewTapped()
        }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.