Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overridable ButtonStyle in SwiftUI

Tags:

swift

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!

like image 443
chkn Avatar asked Oct 11 '19 02:10

chkn


People also ask

How to customize a button style in SwiftUI?

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.

How to create neumorphic button style from viewmodifier in SwiftUI?

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.

What are the requirements of buttonstyle in Swift?

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.

How to use the buttonstyle protocol to create advanced buttons?

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:


1 Answers

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)
    }
}
like image 162
LuLuGaGa Avatar answered Nov 29 '22 16:11

LuLuGaGa