SwiftUI ButtonStyle - how to check if button is disabled or enabled?

后端 未结 3 1331
孤街浪徒
孤街浪徒 2021-01-01 23:27

To style a button in SwiftUI, according to my understanding, you extend ButtonStyle and implement func makeBody(configuration: Self.Configuration) -> s

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 00:11

    I found the answer thanks to this blog: https://swiftui-lab.com/custom-styling/

    You can get the enabled state from the environment by creating a wrapper view and using it inside the style struct:

    struct MyButtonStyle: ButtonStyle {
        func makeBody(configuration: ButtonStyle.Configuration) -> some View {
            MyButton(configuration: configuration)
        }
    
        struct MyButton: View {
            let configuration: ButtonStyle.Configuration
            @Environment(\.isEnabled) private var isEnabled: Bool
            var body: some View {
                configuration.label.foregroundColor(isEnabled ? Color.green : Color.red)
            }
        }
    }
    

    This example demonstrates how to get the state and use it to change the appearance of the button. It changes the button text color to red if the button is disabled or green if it's enabled.

提交回复
热议问题