Label in SwiftUI

swiftui Apr 03, 2024
Label in SwiftUI

One widely used and easily identifiable element in user interfaces involves pairing an icon with a text.

This pattern appears across many kinds of apps and shows up in collections, lists, menus of action items, and disclosable lists, to name a few.

SwiftUI provides us with the built-in solution using the Label view. Simple and elegant. Let's explore how to use it.


Display icon with a title

While displaying a text alone, we have learned about the Text component previously: Insert Link of Text when availableLabel is used to create a standard label for user interface items, consisting of an icon with a title.

struct LabelView: View {
    var body: some View {
        Label("Love you", systemImage: "heart.fill")
    }
}

Result:

We can add more customization with modifiers to our Label just like we did with Text:

Label("Love you", systemImage: "heart.fill")
    .font(.title)
    .fontWeight(.semibold)
    .foregroundStyle(.pink)

Result:

We can also apply styles to labels in several ways using the labelStyle(_:) modifier.

In the case of dynamic changes to the view after device rotation or depending on business logic, we might want to show only the text portion, the icon portion, or both of the label:

VStack(spacing: 15) {
    Label("Rain", systemImage: "cloud.rain")
        .labelStyle(.titleOnly)
    Label("Snow", systemImage: "snow")
        .labelStyle(.iconOnly)
    Label("Sun", systemImage: "sun.max")
        .labelStyle(.titleAndIcon)
}
.font(.title)
.fontWeight(.semibold)
.foregroundStyle(.primary)

Result:

We can achieve this with different label styles: titleOnlyiconOnly, or titleAndIcon.


Separate label style

It’s also possible to make labels using views to compose the label’s icon programmatically:

Label {
    Text("Love you")
        .font(.title2)
        .foregroundStyle(.primary)
} icon: {
    Image(systemName: "heart.fill")
        .font(.title)
        .foregroundStyle(.pink)
}

Result:

This offers us more freedom and control for each part. Instead of using system images, we can load a custom image or use a custom shape for the icon part:

Label {
    Text("Love you")
        .font(.title2)
        .foregroundStyle(.primary)
} icon: {
    Circle()
        .fill(.yellow)
        .frame(width: 8, height: 8)
}

Result:


Conclusion:

The Label view in SwiftUI is a versatile tool for creating clear and visually appealing user interface elements. It combines text with images or other views, allowing for the creation of recognizable and customizable components commonly found in various app interfaces.

Label can be utilized in collections, lists, menus, and other UI contexts, offering a way to present information effectively and intuitively to users.

Signup now to get notified about our
FREE iOS Workshops!