且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SwiftUI ButtonStyle-如何检查按钮是否已禁用?

更新时间:2023-12-05 09:39:46

感谢这个博客,我找到了答案:

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

您可以通过创建包装器视图并在样式struct中使用它来从环境中获取启用状态:

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.