有没有办法从 SwiftUI 中的 ButtonStyle 获取 isDisabled 状态?

Zor*_*ayr 5 ios swift swiftui

我正在制作自己的自定义按钮样式,以简化按钮的外观和感觉。根据按钮是否被禁用,我想改变外观。我发现能够做到这一点的唯一方法是通过isDisabled从顶部传递属性。有没有办法直接从 获取这个ButtonStyle

struct CellButtonStyle: ButtonStyle {

    // Passed from the top... can I get this directly from configuration? 
    let isDisabled: Bool

    func makeBody(configuration: Self.Configuration) -> some View {
        let backgroundColor = isDisabled ? Color.white : Color.black
        return configuration.label
            .padding(7)
            .background(isDisabled || configuration.isPressed ? backgroundColor.opacity(disabledButtonOpacity) : backgroundColor)

    }
}
Run Code Online (Sandbox Code Playgroud)

isDisabled实际的问题是,它会导致创建按钮时处理标志的重复代码:

Button {
    invitedContacts.insert(contact.identifier)
} label: {
    Text(invitedContacts.contains(contact.identifier) ? "Invited" : "Invite")
}
// Passing down isDisabled twice! Would be awesome for the configuration to figure it out directly. 
.disabled(invitedContacts.contains(contact.identifier))
.buttonStyle(CellButtonStyle(isDisabled: invitedContacts.contains(contact.identifier)))
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 4

您可以使用isEnabled环境值,但它不能直接在按钮样式中工作,您需要一些子视图。这是可能方法的演示(您可以通过构造函数注入所有附加参数)

使用 Xcode 12 / iOS 14 进行测试。

struct CellButtonStyle: ButtonStyle {
    
    struct CellBackground: View {
        @Environment(\.isEnabled) var isEnabled       // << here !!
        var body: some View {
            Rectangle().fill(isEnabled ? Color.black : Color.yellow)
        }
    }
    
    func makeBody(configuration: Self.Configuration) -> some View {
        return configuration.label
            .padding(7)
                .background(CellBackground())     // << here !!
    }
}
Run Code Online (Sandbox Code Playgroud)