【问题标题】:Is there a way to get isDisabled state from ButtonStyle in SwiftUI?有没有办法从 SwiftUI 中的 ButtonStyle 获取 isDisabled 状态?
【发布时间】:2020-10-08 01:14:33
【问题描述】:

我正在制作自己的自定义按钮样式以简化按钮的外观和感觉。根据按钮是否被禁用,我想更改外观。我发现能够做到这一点的唯一方法是从顶部传递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)

    }
}

实际问题是在创建按钮时会导致处理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)))

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    您可以使用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 !!
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-23
      • 2012-01-01
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      相关资源
      最近更新 更多