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.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.