Reputation: 24962
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)))
Upvotes: 6
Views: 910
Reputation: 258461
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 !!
}
}
Upvotes: 6