简体   繁体   中英

Enum for ButtonStyle in SwiftUI

It is possible to set the button style this way...?

Button() { }
   .buttonStyle(.default)

Instead of this...?

Button() { }
   .buttonStyle(DefaultButtonStyle())

I tried to code an extension but it doesn't work.

extension ButtonStyle {
    static var `default`: DefaultButtonStyle {
        DefaultButtonStyle()
    }
}

It says: Static member 'default' cannot be used on protocol metatype 'ButtonStyle.Protocol'

Here is a demo of possible approach - use own modifier and own enum, so have complete control on everything.

Usage

Button("Demo") {}
    .myStyle(.default)

And helper extensions

enum MyButtonStyle {
    case `default`
    case borderless
    // .. extend with any custom here
}

extension Button {

    @ViewBuilder
    func myStyle(_ style: MyButtonStyle) -> some View {
        switch style {
            case .default:
                self.buttonStyle(DefaultButtonStyle())
            case .borderless:
                self.buttonStyle(BorderlessButtonStyle())
           // .. extend with any custom here
        }
    }
}

Another solution:

extension ButtonStyle where Self == BorderlessButtonStyle {
    
    internal static var borderless: BorderlessButtonStyle {
        BorderlessButtonStyle()
    }
}

Usage:

Button("Demo") {}
    .buttonStyle(.borderless)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM