Skip to content

ButtonStyle Documentation Example

eawad1 edited this page Jan 21, 2021 · 1 revision

This protocol is used to create a custom button style.

The ButtonStyle protocol provides a template to create a reusable style for your buttons. It also provides data about the button and its interaction state.

To make a custom style, create a new structure that conforms to ButtonStyle. This new style can be easily reused across your application. The style adapts to the user's current interaction state (i.e. on press, on release).

Your structure only needs to implement one method: ButtonStyle/makeBody(configuration:).

To change the style of your Button, use the View/buttonStyle(_:) method. This method accepts a ButtonStyle.

ButtonStyle Example 1

struct ExampleView: View {
    var body: some View {
        Button("Banana🍌🍌", action: { tap() })
            .buttonStyle(BananaButtonStyle(color: .yellow))
    }

    func tap() { }
}

struct BananaButtonStyle: ButtonStyle {
    var color: Color
    func makeBody(configuration: Self.Configuration) -> some View {
        BananaButton(configuration: configuration, color: color)
    }

    struct BananaButton: View {
        let configuration: BananaButtonStyle.Configuration
        let color: Color

        var body: some View {
            configuration.label
                .padding()
                .background(RoundedRectangle(cornerRadius: 10).fill(color))
                .scaleEffect(configuration.isPressed ? 0.8: 1)
                .animation(.spring())
        }
    }
}

Button style applies to all buttons within a view hierarchy. For example, you could apply ButtonStyle to a VStack.

ButtonStyle Example 2

struct ExampleView: View {
    var body: some View {
        VStack {
            Button("🍌🍌", action: { tap() })
            Button("🍎🍎", action: { tap() })
            Button("πŸ‘πŸ‘", action: { tap() })
        }
        .buttonStyle(BananaButtonStyle(color: .yellow))
    }

    func tap() {}
}

struct BananaButtonStyle: ButtonStyle {
    var color: Color
    func makeBody(configuration: Self.Configuration) -> some View {
        BananaButton(configuration: configuration, color: color)
    }

    struct BananaButton: View {
        let configuration: BananaButtonStyle.Configuration
        let color: Color

        var body: some View {
            return configuration.label
                .padding()
                .background(RoundedRectangle(cornerRadius: 10).fill(color))
                .scaleEffect(configuration.isPressed ? 0.8: 1)
                .animation(.spring())
        }
    }
}

For more on how to customize your button style body, check out ButtonStyle/makeBody(configuration:). To provide greater control over when and how a button triggers it's action use PrimitiveButtonStyle. While this property requires more work to setup, it provides more customization. @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)

Clone this wiki locally