How to Use Form in SwiftUI: Simple Guide with Examples
In SwiftUI, you use the
Form view to create forms that group input controls like text fields and toggles. Wrap your input elements inside Form { ... } to get a styled, scrollable form automatically. This makes building user input screens easy and consistent.Syntax
The Form view acts like a container for input controls. Inside it, you place views such as TextField, Toggle, and Picker. SwiftUI automatically styles and arranges these controls in a grouped list style.
Basic syntax:
Form { ... }: The container for form elements.- Input controls inside the braces.
swift
Form {
TextField("Enter name", text: $name)
Toggle("Enable feature", isOn: $isEnabled)
}Output
A form with a text field labeled 'Enter name' and a toggle labeled 'Enable feature'.
Example
This example shows a simple form with a text field and a toggle. The form automatically arranges the inputs and provides a native iOS look.
swift
import SwiftUI struct ContentView: View { @State private var name = "" @State private var isEnabled = false var body: some View { NavigationView { Form { Section(header: Text("User Info")) { TextField("Enter your name", text: $name) Toggle("Enable notifications", isOn: $isEnabled) } } .navigationTitle("Settings") } } }
Output
A screen titled 'Settings' with a form containing a section labeled 'User Info' that has a text field and a toggle switch.
Common Pitfalls
Common mistakes when using Form include:
- Not using
@Stateor other property wrappers to bind input values, so inputs don’t update. - Placing
Forminside views that conflict with its scrolling behavior. - Forgetting to use
Sectionto group related inputs for better UI.
Always bind inputs to state variables and use Section for clarity.
swift
/* Wrong: No binding, input won't update */ Form { TextField("Name", text: .constant("")) } /* Right: Bind to @State variable */ @State private var name = "" Form { TextField("Name", text: $name) }
Output
The wrong code shows a text field that cannot be edited; the right code allows user input to update the state.
Quick Reference
Tips for using Form in SwiftUI:
- Use
Formto group input controls with native styling. - Bind inputs to
@Stateor other reactive properties. - Use
Sectionto organize inputs logically. - Wrap
ForminNavigationViewfor titles and navigation.
Key Takeaways
Use
Form to create grouped input screens with native iOS style.Bind form inputs to
@State variables to capture user input.Organize inputs with
Section for better readability and UI.Wrap forms in
NavigationView to add titles and navigation controls.