To style a button in SwiftUI, according to my understanding, you extend ButtonStyle
and implement func makeBody(configuration: Self.Configuration) -> some View
within which you start applying modifications to the configuration.label
which is a reference to the Button
view.
Now, besides the label
field, ButtonStyle.Configuration
has a boolean field for isPressed
, but that's seems to be all.
How do I check if the button is enabled or disabled?
For example, I want to draw a border around the button, and I want the border to be blue if the button is enabled and gray if disabled.
My first guess is something like this:
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.overlay(
RoundedRectangle(cornerRadius: 4).stroke(configuration.isEnabled ? Color.blue : Color.gray, lineWidth: 1).padding(8)
)
}
But there's no isEnabled
field.
The Apple-supplied PlainButtonStyle
obviously has access to this information, as the doc comment in the header file that declares it says 'The style may apply a visual effect to indicate the pressed, focused, or enabled state of the button.'
/// A `Button` style that does not style or decorate its content while idle.
///
/// The style may apply a visual effect to indicate the pressed, focused,
/// or enabled state of the button.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct PlainButtonStyle : PrimitiveButtonStyle {
.....
Is there a way to access this information?
EDIT:
Before you suggest closing this question, please read this:
There's a similar question asked a while ago. That question does not specify any context.
Here I have a specific context: creating a generic reusable button style.
The answer provided there does not suffice. I can't expect people to pass the disabled state to the style constructor. That's too much duplication of effort.
Can you imagine if people have to write code this way:
Button() { .... }.disabled(someExprssion).buttonStyle(MyCustomStyle(disabled: someExpression))
Clearly that's not desireable.
Also clearly the Apple supplied style has access to the information without requiring people to pass the disable state again to the style.
If you close the question, you will forever prevent anyone from providing a useful answer to this question on StackOverflow.
Please reconsider before you propose closing.
EDIT2:
I have a guess that if you can get the EnvironmentValues.isEnabled
of the Button
view then it might be the right value.
So another way to ask the question is: is it possible in SwiftUI to get the environment of a view that you didn't define yourself?
See Question&Answers more detail:
os