简体   繁体   English

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

[英]Is there a way to get isDisabled state from ButtonStyle in SwiftUI?

I am making my own custom button style to simplify my button's look & feel.我正在制作自己的自定义按钮样式以简化按钮的外观和感觉。 Based on if the button is disabled, I would like to change the look.基于按钮是否被禁用,我想改变外观。 The only way I have found to be able to do this is through passing isDisabled property from the top.我发现能够做到这一点的唯一方法是从顶部传递isDisabled属性。 Is there a way to get this directly from ButtonStyle ?有没有办法直接从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)

    }
}

The actual problem is that it leads to duplicate code for handling isDisabled flag when creating the button:实际问题是它会导致在创建按钮时处理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)))

You can use isEnabled environment value, but it does not work directly in button style, you need some sub-view.您可以使用isEnabled环境值,但它不能直接在按钮样式中工作,您需要一些子视图。 Here is a demo of possible approach (all your additional parameters you can inject via constructor)这是一个可能的方法演示(您可以通过构造函数注入的所有附加参数)

Tested with Xcode 12 / iOS 14.使用 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 !!
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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