Label pairs an icon with a title, the most common interface atom there is. It beats a
hand-rolled HStack because it merges icon and title into one accessibility element with the
title as the label, and because LabelStyle restyles every label from one place.
Creating Labels
The initializer takes a title (string or LocalizedStringKey) and either an SF Symbol name
or a bundle image name. A ViewBuilder overload accepts arbitrary views for both slots.
Label("Heart Rate", systemImage: "heart.fill")
Label("ECG", image: "ecg")
Label {
Text("Hello")
} icon: {
Image(systemName: "heart")
}
Built-in Styles
Three styles ship with SwiftUI: DefaultLabelStyle (icon and title), IconOnlyLabelStyle,
and TitleOnlyLabelStyle. The icon-only style keeps the title as the accessibility label,
so a toolbar of bare icons stays usable with VoiceOver.
Label("Heart Rate", systemImage: "heart.fill")
.labelStyle(IconOnlyLabelStyle())
Custom Styles
LabelStyle follows the standard style-protocol shape: one makeBody(configuration:) with
configuration.icon and configuration.title. This style stacks vertically for
accessibility text sizes and horizontally otherwise.
struct AccessibleLabelStyle: LabelStyle {
@Environment(\.sizeCategory) var sizeCategory
@ViewBuilder
func makeBody(configuration: Configuration) -> some View {
if sizeCategory.isAccessibilityCategory {
VStack {
configuration.icon
configuration.title
}
} else {
HStack {
configuration.icon
configuration.title
}
}
}
}
Button(action: {}) {
Label("Heart Rate", systemImage: "heart.fill")
}
.labelStyle(AccessibleLabelStyle())
labelStyle propagates through the environment, so one modifier on a container styles every
label beneath it.