SwiftUI Button can't tap on a background
Table of Contents
The tappable area of a button is dictated by its content.
The content of a button is any view that we provide as a button's label.
In the following example, the button's content is the Text("Button Content")
.
Button {
print("Tap")
} label: {
// 1
Text("Button Content")
}
// 2
.foregroundColor(.white)
.padding(.vertical, 20)
.padding(.horizontal, 40)
.background(.pink)
.cornerRadius(8)
1 The tappable area in this case is the Text("Button Content")
view.
2 Other modifiers we applied outside a button aren't part of the button.
It might look like a part of a button, but it isn't. We can't trigger the button action by tapping the padding and background.
You can easily support sarunw.com by checking out this sponsor.
AI Grammar: Correct grammar, spell check, check punctuation, and parphrase.
How to make SwiftUI Button background tappable
To make a background of a button tappable, you need to include it inside a button's label.
By moving all modifiers inside a button's label, they become part of a button, making it count as a tappable area.
Button {
print("Tap")
} label: {
Text("Button Content")
.foregroundColor(.white)
.padding(.vertical, 20)
.padding(.horizontal, 40)
.background(.pink)
.cornerRadius(8)
}
We move every modifier in a button's label. This makes it possible to activate a button by tapping the background.
Read more article about SwiftUI, Button, or see all available topic
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.
Become a patron Buy me a coffee Tweet ShareHow to Disable swipe down to dismiss Sheet in SwiftUI
By default, you can dismiss a sheet presentation using a swipe-down gesture. But you might don't want this behavior on every sheet. Learn how to disable it in SwiftUI.
How to preview UIView in Xcode Previews
If you use UIKit, you can preview your view using Interface Builder. But you can also preview a custom view that is created programmatically using Xcode Previews.