'SwiftUI Button has extended tap area
I've recently started using SwiftUI and I'm noticing that the tap area of a Button always extends around it which creates problems for some of my UIs. Here's my sample code in the playground (Using Xcode 13.3). The same thing can be observed on a physical iOS device:
struct TestView: View {
var body: some View {
VStack {
Button("Tap me") {
print("tap")
}
.background(Color.yellow)
}
.frame(width: 300, height: 500)
}
}
PlaygroundPage.current.liveView = UIHostingController(rootView: TestView())
This demonstrates how far the tap area extends around the button:

First off, I couldn't find any information regarding this in the documentation. If I've missed something, can anybody point me to a page/WWDC video/a comment where this behaviour is explained or mentionted?
Second, according to multiple discussions here and in other forums, you should use the contentShape() modifier to change this behaviour. So I modified the above code like this:
Button("Tap me") {
print("tap")
}
.background(Color.yellow)
.contentShape(Rectangle())
Which produces this result:

There IS a difference, but it is trivial and not at all what I need. I need the tap area to extend only to the visible bounds of the button. I've tried to modify the shape using scale() and inset() both of which kind-of worked. It seems that the contentShape() modifier extends the tap area beyond the provided shape. This can be tested by providing your own custom shape. The shape receives the visible size of the button in the rect in the path(in:) function. Whatever path is returned from there, contentShape() adds its own magic numbers. The only solution I can think of is something along the lines of creating my own shape that negates those magic numbers. Are there any other solutions? Can some of the more experienced SwiftUI users out there share their thoughts on this?
Solution 1:[1]
Why not try using buttonStyle's try .borderedProminent. A great article is here by swiftwithmajid about SwiftUI Button's. It helped me solved a button issue I was having.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cole |
