How it works
FormStyle is the protocol that defines the appearance and layout behavior of a Form. A form gathers labeled controls, but the way those controls are spaced, grouped, and aligned is the job of its style, and FormStyle is the type that encapsulates that presentation so it can be swapped without touching the form's contents. SwiftUI ships several conforming styles, and you select one by passing it to the formStyle(_:) modifier rather than constructing the style directly. Reach for it when you want a form to adopt a platform-appropriate look, or when a screen needs a presentation other than the inherited default.
Apply a style with formStyle(_:)
FormStyle takes effect through the formStyle(_:) modifier, which sets the style for the Form it wraps and any forms nested inside. In the example,
.formStyle(.grouped)is attached to theForm, telling SwiftUI to lay its sections out in the grouped presentation.Choose a built-in conforming style
You rarely conform to FormStyle yourself; instead you pass one of the provided values such as
.grouped,.columns, or.automatic. Here.groupedis a GroupedFormStyle that renders each Section as an inset, rounded block with its header, giving the settings-style appearance.Let the style arrange the form's content
The style governs how a Form's
Sectiongroups, their headers, and the rows within are spaced and aligned, so you describe the data and let the style handle layout. TheSection("Profile")andSection("About")blocks supply that structure, and the grouped style draws the visual separation between them.Style controls without changing them
Because FormStyle works at the form level, the individual controls stay declarative and style-agnostic. The
TextField("Name", text: $name)andToggle("Notifications", isOn: $notify)are written once and pick up grouped formatting from the surrounding style rather than from per-control modifiers.Rely on inheritance through the environment
formStyle(_:) propagates the chosen FormStyle down the view hierarchy, so a style set on an outer container reaches every Form beneath it. In this view the modifier sits directly on the
Form, but the same call placed higher up would style nested forms identically through the environment.
.formStyle(.grouped) to .formStyle(.columns) to see the same sections re-laid out by a different FormStyle without altering any of the controls.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct FormStyleDemo: View {
@State private var notify = true
@State private var name = "Ada"
var body: some View {
Form {
Section("Profile") {
TextField("Name", text: $name)
Toggle("Notifications", isOn: $notify)
}
Section("About") {
Text("Grouped form style")
}
}
.formStyle(.grouped)
.padding()
}
}