SwiftUI Form: build forms with TextField, Picker and validation
SwiftUI Form explained: build forms with TextField, Toggle and Picker, choose the right keyboard, validate input and use FocusState.
You build a form in SwiftUI with the Form container: put input controls such as TextField, Toggle, Picker and DatePicker inside, group them with Section and bind each one to a state variable using $. SwiftUI handles the styling, which on iPhone looks like the Settings app.
This post walks through a complete form, the right keyboard, simple validation and moving from field to field.
A form with Form and Section
Every control needs a value it can read and write. To begin with, @State is enough. Section gives the form headers and visible groups.
enum Plan: String, CaseIterable, Identifiable {
case free, pro
var id: Self { self }
var title: String { rawValue.capitalized }
}
struct ProfileForm: View {
@State private var name = ""
@State private var email = ""
@State private var notifications = true
@State private var birthday = Date.now
@State private var plan = Plan.free
var body: some View {
Form {
Section("Profile") {
TextField("Name", text: $name)
TextField("Email", text: $email)
}
Section("Settings") {
Toggle("Notifications", isOn: $notifications)
DatePicker("Birthday", selection: $birthday,
displayedComponents: .date)
Picker("Plan", selection: $plan) {
ForEach(Plan.allCases) { plan in
Text(plan.title).tag(plan)
}
}
}
}
}
}Inside a Form, the Picker shows a menu automatically. The type in tag has to match the type of the selection exactly, otherwise the picker will not respond.
The right keyboard for every TextField
Typing an email address on the standard keyboard is tedious. A few modifiers give the field the matching keyboard, suggest saved addresses and switch off capitalisation and autocorrection.
TextField("Email", text: $email)
.keyboardType(.emailAddress)
.textContentType(.emailAddress)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()For passwords, use SecureField instead of TextField. For numbers there is .keyboardType(.numberPad) or .decimalPad, and a TextField can bind straight to a number through its format parameter.
Validate input and disable Save
The simplest validation is a computed property. While it returns false, the button stays disabled and a footer note explains what is missing.
private var isValid: Bool {
!name.trimmingCharacters(in: .whitespaces).isEmpty
&& email.contains("@")
}
// im Form:
Section {
Button("Save") { save() }
.disabled(!isValid)
} footer: {
if !isValid {
Text("Please enter a name and a valid email address.")
}
}Only check in the form what makes it easier to use. Whether an address really exists is for the server to decide.
Move between fields with FocusState
Good forms can be filled in without tapping the next field. @FocusState controls which field is active, and the return key moves on.
enum Field { case name, email }
@FocusState private var focus: Field?
TextField("Name", text: $name)
.focused($focus, equals: .name)
.submitLabel(.next)
.onSubmit { focus = .email }
TextField("Email", text: $email)
.focused($focus, equals: .email)
.submitLabel(.done)
.onSubmit { focus = nil }Setting focus to nil dismisses the keyboard. Adding .scrollDismissesKeyboard(.interactively) to the Form also lets it slide away while scrolling.
Common questions
- Form or List? Form is meant for input and settings, List for data you display and search. More on lists in SwiftUI List.
- Where does the form go? Usually in a sheet with Cancel and Save in the toolbar, as described in SwiftUI sheet.
- Where does the data go? With more than a handful of fields a model of its own pays off, see @Observable in SwiftUI. To store it permanently, use SwiftData.