:codable (karma)

A mobile engineer trying to figure out how to be a good father

Using ButtonStyles to create reusable button styles

When creating a design system, or even just an application theme you want to create small modules of code that can be reused quickly and easily.

This really comes into play with SwiftUI and modifiers. Say for instance you have a button which you want to use in a primary (meaning main view action across your application) which you want to have a corner radius, a black background with white text.

If you add padding into the mix and you end up with something like

Button(action: {
    // Do something
}) {
    Text("Hello world")
        .bold()
        .foregroundColor(.white)
        .frame(minWidth: 0, maxWidth: .infinity, maxHeight: 15)
        .padding()
        .background(.red)
        .cornerRadius(10)
        .padding(.horizontal, 16)
}

Having to duplicate this wherever we want this specific button add a lot of lines to our codebase as well as increasing the chances of mistakes, lowering the consistency and feel of the app.

Thankfully we have ButtonStyles!

A ButtonStyle is a custom object used in a Button modifier to keep styling consistent.

struct RedBackgroundButtonStyle: ButtonStyle {

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .bold()
            .foregroundColor(.white)
            .frame(minWidth: 0, maxWidth: .infinity, maxHeight: 15)
            .padding()
            .background(.red)
            .cornerRadius(10)
            .padding(.horizontal, 16)
    }
}

To use our new style simply add the correct modifier

.buttonStyle(RedBackgroundButtonStyle())

Which adds all the custom modifiers to any button you want taking the initial code sample, down to

Button(action: {
    // Do something
}) {
    Text("Hello world")
}
.buttonStyle(RedBackgroundButtonStyle())

Allowing for easier abstraction and code reuse across your project.

Tagged with: