Using ButtonStyle
protocol, you can define styles for your SwiftUI buttons and can use them across your entire app for multiple buttons. You have to create a new struct that conforms to the ButtonStyle protocols.
If you use the inline modifier to customize your button design for multiple buttons across the app, then it is going to be a time-consuming task:
Button("Tap Me") {
print("Button tapped!")
}
.padding()
.background(.green)
.foregroundColor(.white)
.cornerRadius(16)
As you can see in the above code, we have used some modifiers to style the button using modifiers inline. But if we want the same style for multiple buttons in the app, we can simply use the ButtonStyle protocol.
Buttonstyle
is a protocol or type that applies standard interaction behavior as well as a custom appearance to all buttons within a view hierarchy.
The main purpose of using ButtonStyle type is to write once and using for multiple buttons where you want the same style and design. It reduces the amount of code by preventing you from repeating some code.
Below is given an example where we have created a struct GreenBtn
that conforms to ButtonStyle
protocol:
struct GreenBtn: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.background(.green)
.foregroundColor(.white)
.cornerRadius(16)
}
}
As you can see, we have declared the same modifiers that we used in the button previously.
Below is how to apply it to a button:
Button("Tap Me") {
print("Button tapped!")
}
.buttonStyle(GreenBtn())
For better understanding, let’s see an example with complete code:
import SwiftUI
// Creating our struct for Button Style
struct GreenBtn: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.background(.green)
.foregroundColor(.white)
.cornerRadius(16)
}
}
struct ContentView: View {
var body: some View {
Button("Tap Me") {
print("Button tapped!")
}
.buttonStyle(GreenBtn())
Button("Tap Another Button") {
print("Second Button tapped!")
}
.buttonStyle(GreenBtn())
}
}
In the above example, we have created a struct GreenBtn and applied it to 2 different buttons. If you run the above code, it will look something as you can see in the below screenshot: