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.
[Read more…]