chkn
chkn

Reputation: 717

Overridable ButtonStyle in SwiftUI

I'm trying to create a custom ButtonStyle that supplies some defaults but is also overridable.

For instance, on iOS, DefaultButtonStyle colors the text blue by default, but you can override that by specifying a foregroundColor modifier. Likewise, PlainButtonStyle colors the text black by default but is also overridable:

example of overriding foreground color in button styles

So clearly, it's possible to create a button style that is overridable. However, if I simply create one that sets the foreground color like so, it is not overridable:

public struct CustomButtonStyle: ButtonStyle {
    public func makeBody(configuration: Self.Configuration) -> some View
    {
        configuration.label
            .foregroundColor(Color.blue)
    }
}

example of not being able to override foreground color in custom button style

How can I make a ButtonStyle that supplies a default foreground color but is also overridable?

Thanks in advance!

Upvotes: 9

Views: 1837

Answers (1)

LuLuGaGa
LuLuGaGa

Reputation: 14388

You can implement it like this:

public struct CustomButtonStyle: ButtonStyle {

    let color: Color

    public init(color: Color = .accentColor) {
        self.color = color
    }

    public func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(color)
    }
}

Upvotes: 2

Related Questions