Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if user tapped the screen, including Buttons, in SwiftUI

Tags:

swiftui

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")
    }
}
like image 941
Ryan Douglas Avatar asked Jan 19 '26 21:01

Ryan Douglas


1 Answers

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


.simultaneousGesture(
    TapGesture()
        .onEnded {
            viewTapped()
        }
)
like image 96
Mojtaba Hosseini Avatar answered Jan 21 '26 21:01

Mojtaba Hosseini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!