swiftswiftui

How can I know if a SwiftUI Button is enabled/disabled?


There is no isEnabled property for a SwiftUI button. How can i tell if it is enabled?

In regular UIKit, i would simply do

if button.isEnabeld == true {
} else {
}

but there is no SwiftUI equivalent.


Solution

  • The whole idea of SwiftUI, is to avoid duplication of the source of truth. You need to think differently, and consider where the source of truth is. This is where you need to go to find out the button's state. Not from the button itself.

    In "Data Flow Through SwiftUI", at minute 30:50, they explain that every piece of data has a single source of truth. If your button gets its state from some @Binding, @State, @EnvironmentObject, etc, your if statement should get that information from the same place too, not from the button.