How it works
LabelStyle is the protocol that defines how a Label arranges and presents its title and icon. Rather than hard-coding whether a label shows text, a glyph, or both, you express that decision as a style and apply it with the labelStyle(_:) modifier, letting a single Label adapt to different contexts. Reach for it when you want consistent label presentation across a view hierarchy, or when a particular placement calls for icon-only or title-only treatment without rebuilding the label itself.
Start from a
Labelwith a title and iconLabelStyleoperates on the standardLabel, which pairs a text title with a symbol. Every label in the example supplies both pieces, as inLabel("Icon Only", systemImage: "heart.fill"), so a style has both a title and an icon to lay out or selectively hide.Apply a style with
labelStyle(_:)The
labelStyle(_:)view modifier attaches aLabelStyleto a label (or to a container, cascading to the labels within it). The chosen style decides the final composition, soLabel("Title Only", systemImage: "bell").labelStyle(.titleOnly)produces text alone even though the label still declares an icon.Choose a built-in style value
SwiftUI ships ready-made conformances exposed as static members you can pass to the modifier. The example exercises
.iconOnly,.titleOnly, and.titleAndIcon, each instructing the same kind ofLabelto surface just the glyph, just the text, or both together.Rely on the default when no style is set
A label with no
labelStyle(_:)applied uses the environment's default presentation, typically title and icon side by side. The firstLabel("Default", systemImage: "star")has no modifier, so it renders with the inherited style and serves as a baseline against the explicitly styled labels.
.labelStyle(.titleAndIcon) on the Label("Title & Icon", systemImage: "flag") to .iconOnly and watch the same label collapse to just its glyph.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 LabelStyleDemo: View {
var body: some View {
VStack(spacing: 16) {
Label("Default", systemImage: "star")
Label("Icon Only", systemImage: "heart.fill")
.labelStyle(.iconOnly)
Label("Title Only", systemImage: "bell")
.labelStyle(.titleOnly)
Label("Title & Icon", systemImage: "flag")
.labelStyle(.titleAndIcon)
}
.padding()
}
}