SwiftUI Button: Making Background Tappable
In this tutorial, We will see how to make the background of a SwiftUI button tappable.
If you have faced issues with SwiftUI buttons where the background doesn’t respond to taps, you might be facing a common challenge.
In SwiftUI, the tappable area of a button is determined by its content, which we include within the label of the button.
Understanding Button Interaction
When we create a button using SwiftUI, the part of the button that we can tap is initially defined by whatever we put inside the button as its label
. The area we can touch to activate the button is determined by the content we include inside it.
If we have a text, image, or any other view as the label of the button, the size and shape of the tappable area will be the same as the text, image, or any other view.
Example
Button { // Button action goes here } label: { Text("Press Button") }
Here, the tappable area of the button is the Text
view which is “Press Button“. We can trigger the button action by tapping specifically on the text.
Output:
Modifying the Button Appearance
Now, I will modify the button’s appearance by adding some padding, background color, and corner radios to make the button more attractive.
Then we will see whether the padding area or background is clickable or not.
Example
Button { // Button action goes here } label: { Text("Press Button") } .padding(40) .background(.mint) .cornerRadius(6)
In the above program, I have made the button look awesome with some padding, corner radius, and a mint colored background.
Output:
As you can see in the output, only the text part is still tappable. If we tap on the background or the space around the text, nothing happens.
This is because we have applied those modifiers on the button not within the label
of the button. So, we have to apply those modifiers within the label of the button to make the background tappable.
Making the Background Tappable
As I have mentioned earlier “The tappable area of a button is determined by its content, which we include within the label of the button“.
So, to make the background tappable we just have to apply those modifiers on the Text
view within the label
of the button.
Example
Button { // Button action goes here } label: { Text("Press Button") .padding(40) .background(.mint) .cornerRadius(6) }
Now, we can trigger the button action by tapping anywhere within the button’s visual boundaries.
Output:
Leave a Reply