Skip to main content

Enabling and disabling elements in forms

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

Enabling and disabling elements in forms 관련

SwiftUI by Example

Back to Home

Enabling and disabling elements in forms | SwiftUI by Example

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)
            }
        }
    }
}

Download this as an Xcode projectopen in new window

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.

Similar solutions…
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
Bindings and forms | SwiftUI by Example

Bindings and forms
Breaking forms into sections | SwiftUI by Example

Breaking forms into sections
Working with forms | SwiftUI by Example

Working with forms

이찬희 (MarkiiimarK)
Never Stop Learning.