How it works
A GroupBox is a stylized container that visually groups a set of related views under an optional label, giving them a shared background and a clear sense of belonging together. Reach for it when several controls or pieces of content form one logical unit — a block of settings, a form section, or a labeled panel — and you want the platform to draw the surrounding chrome for you. Unlike a plain VStack, a GroupBox conveys grouping semantically and adopts a consistent, platform-appropriate appearance through its box style.
Compose the grouped content in the trailing closure
The content closure is GroupBox's primary slot: every view you place there becomes part of one visually grouped unit, laid out as if in an implicit VStack. Here the two
Togglecontrols,NotificationsandSounds, are written inside theGroupBox { ... }closure so they read as a single block of preferences rather than loose, unrelated controls.Title the box with the label closure
The
label:closure supplies the heading that names what the group is about; it accepts any view, so you are not limited to plain text. In the example the label is aLabel("Preferences", systemImage: "gear"), which pairs a title with an SF Symbol and renders above the grouped content as the box's caption.Use the convenience initializers for simpler labels
Beyond the content-plus-label form shown here, GroupBox offers initializers that take a
StringorLocalizedStringKeytitle directly, and one that takes content alone with no label at all. The example'sGroupBox(content:label:)is the most flexible variant; swap toGroupBox("Preferences") { ... }when a plain text title is all you need.Restyle with groupBoxStyle(_:)
GroupBox renders through a GroupBoxStyle, and the
.groupBoxStyle(_:)modifier lets you choose or supply one to change the background, corner treatment, and label placement for every box in a subtree. Applying it to theGroupBoxhere — or to an ancestor of it — overrides the default appearance without touching the content orlabel:.Treat the box as a normal view in layout
A GroupBox is itself a
View, so it participates in layout and accepts standard modifiers around its outer edge. The trailing.padding()in the example operates on the whole box, insetting it from its container while leaving the internal grouping intact.
Toggle("Badges", isOn: .constant(true)) inside the GroupBox { ... } closure and watch the shared background and label stretch to enclose it automatically.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 GroupBoxDemo: View {
var body: some View {
GroupBox {
Toggle("Notifications", isOn: .constant(true))
Toggle("Sounds", isOn: .constant(false))
} label: {
Label("Preferences", systemImage: "gear")
}
.padding()
}
}