Reputation: 717
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:
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)
}
}
How can I make a ButtonStyle
that supplies a default foreground color but is also overridable?
Thanks in advance!
Upvotes: 9
Views: 1837
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