In this tutorial we’ll be looking at how to create your own custom button style. Although SwiftUI does provide great default styles, many apps use their own style to match the unique design of their app. This can be accomplished with the ButtonStyle protocol that allows you to chose different effects from colours to shadows and then apply the style across all Buttons in the app giving a consistent style that can easily be altered if needed.
First, create a struct that conforms to ButtonStyle:
struct CustomButtonStyle: ButtonStyle {
var buttonColor: Color?
var shadowRadius: CGFloat?
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.background(Color(buttonColor ?? Color.blue))
.foregroundColor(.white)
.cornerRadius(10)
.shadow(radius: shadowRadius ?? 0)
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.animation(.easeInOut(duration: 0.2), value: configuration.isPressed)
}
}
In this code, we have two optional variables that allow us to either take a colour parameter and radius parameter, or just let the custom button set to defaults.
The makeBody method defines the visual appearance and behaviour of the button. Here you can set what it will look like. makeBody is required by the ButtonStyle protocol, so must be implemented.
Now that we have defined our custom button, called CustomButtonStyle, we can now make use of this in our view(s) as follows:
struct ContentView: View {
var body: some View {
VStack {
Button("Test") {
print("Custom Button Tapped!")
}
.buttonStyle(CustomButtonStyle())
Button("Test") {
print("Custom Button Tapped!")
}
.buttonStyle(CustomButtonStyle(buttonColor: Color.green, shadowRadius: 2))
}
}
}
Our first button in the VStack passes in no parameters, so the button style defaults to a blue button with 0 shadow.
The second button in the stack does pass in params, so we get a green button with a shadowRadius set to 2.
By implementing the custom ButtonStyle protocol, you can now make use of this button style anywhere in a ButtonView, thus making changes to shadow or other settings be quickly shown across the whole app.
Leave a Reply
You must be logged in to post a comment.