SwiftUI Button: Inaccurate tap area. How should I fix it?

A simple button in SwiftUI does not have an accurate tap area. It's supposed to react to the tap gesture only when the user is tapping inside the bounds. But it's not.

iOS 14.5

Xcode 12.5.1 (12E507)

Answered by frogcjn in 683166022

It is the right result. The tap area is larger than the Button border. If you want to adjust the tap area, you should adjust the code. For example, use Rectangle with .onTapGesture

You may be looking at the mouse pointer?
Look at the circle (which represents a finger) instead.
The tap area is clearly intersecting the button.

And of course, this is the simulator.
Have you found a problem when running on actual devices?

Accepted Answer

It is the right result. The tap area is larger than the Button border. If you want to adjust the tap area, you should adjust the code. For example, use Rectangle with .onTapGesture

I was also surprised by the tap area being larger than the frame of the button.

By accident I found that if you insert a UIKit view behind the SwiftUI button then the tap area on the button will behave as expected. No idea if this is bug or not.

struct ContentView: View {
    var body: some View {

        ZStack {
            UIKitView()
                .ignoresSafeArea()
            
            Button("Hell, world") {}
                .border(Color.black)
        }
    }
}

#Preview {
    ContentView()
}

struct UIKitView: UIViewRepresentable {

    func makeUIView(context: Context) -> UIView {
        return UIView()
    }

    func updateUIView(_ view: UIView, context: Context) {}
}
SwiftUI Button: Inaccurate tap area. How should I fix it?
 
 
Q