Updated for Xcode 14.2
SwiftUI lets us disable any part of its forms or even the whole form, all by using the disabled()
modifier. This takes a single Boolean that defines whether the element should be disabled or not. The form element’s style automatically gets updated to reflect its status – buttons and toggles get grayed out, for example.
For example, this creates a form with two sections: one containing a toggle, and one containing a button that is enabled only when the toggle is on:
struct ContentView: View {
@State private var agreedToTerms = false
var body: some View {
Form {
Section {
Toggle("Agree to terms and conditions", isOn: $agreedToTerms)
}
Section {
Button("Continue") {
print("Thank you!")
}
.disabled(agreedToTerms == false)
}
}
}
}
Download this as an Xcode project
As you can see, the button is disabled just by adding disabled(agreedToTerms == false)
to the list of modifiers.
Like many other SwiftUI modifiers, you can lift disabled()
so that it’s run on the section or even the whole form depending on what behavior you want – just move it to come after the section, for example.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.