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!
SwiftUI makes it very easy to customize a button style. The ButtonStyle protocol works similarly to the ViewModifier protocol, except it's specialized for buttons. You can see that we can use the same code and make it more structural and reusable with a little effort just by knowing the framework feature.
To make a neumorphic button style out of view modifier, we just simply copy all modifiers that we use to make our neumorphic design and put it in a newly create ViewModifier. The code is pretty much the same from How to create Neumorphic design in SwiftUI. I just create a ViewModifier out of it.
The only requirement of ButtonStyle is to return a view from makeBody (configuration:), the function takes in a ButtonStyleConfiguration instance: public struct ButtonStyleConfiguration { public let label: ButtonStyleConfiguration.
Using ButtonStyle protocol allows you to create advanced button styles and introduce animations to the button style when it is being pressed. Let’s start with a simple button: Now, let’s create new struct called GradientButtonStyle which implements the ButtonStyle protocol and applies a gradient to the button’s design/background color:
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With