Enabling and disabling elements in forms
Enabling and disabling elements in forms 관련
Updated for Xcode 15
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)
}
}
}
}
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.