简体   繁体   中英

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. Is there a way to get this directly from 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:

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. Here is a demo of possible approach (all your additional parameters you can inject via constructor)

Tested with 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 !!
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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