Logo for tanaschita.com

Customizing buttons in SwiftUI with the ButtonStyle protocol

Learn how to reuse button styles in SwiftUI.

23 May 2022 · 2 min read

SwiftUI provides a ButtonStyle protocol which allows us to create reusable button styles without having to create new views.

Let's directly jump into an example.

When working with buttons in SwiftUI, we use modifiers to customize them.

Button("Primary button", action: {
})
.padding(.horizontal, 20)
.padding(.vertical, 10)
.foregroundColor(.white)
.background(colorScheme.primaryColor)
.clipShape(RoundedRectangle(cornerSize: CGSize(width: 10, height: 10)))

To reuse this button style in multiple views, SwiftUI offers the ButtonStyle protocol which allows us to apply the style with the buttonStyle modifier.

Button("Primary button", action: {
})
.buttonStyle(PrimaryButtonStyle())

The only requirement of the ButtonStyle protocol is to implement the makeBody function.

struct PrimaryButtonStyle: ButtonStyle {
private let colorScheme = ColorScheme()
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(.horizontal, 20)
.padding(.vertical, 10)
.foregroundColor(.white)
.background(.red)
.clipShape(RoundedRectangle(cornerSize: CGSize(width: 10, height: 10)))
}
}

The makeBody function provides a configuration that we can use to add our styling. It also provides the property isPressed which indicates whether the user is currently pressing the button.

.foregroundColor(configuration.isPressed ? .brown : .red)

Another benefit we get is that we can set the button style in the environment of a view.

VStack(spacing: 10) {
Button("Primary button 1") {}
Button("Primary button 2") {}
Button("Primary button 3") {}
}
.buttonStyle(PrimaryButtonStyle())

Setting the button style on the VStack will automatically apply it to all the buttons inside the view.

Newsletter

Like to support my work?

Say hi

Related tags

Articles with related topics

Latest articles and tips