How to display an icon with a title using the Label in SwiftUI


Greetings, traveler!

SwiftUI provides a straightforward way to display text and icons together using the Label view.

You can use it with SF Symbols:

struct ContentView: View {

    var body: some View {
        Label("Favorites", systemImage: "star")
    }
    
}

Or with custom Images

struct ContentView: View {

    var body: some View {
        Label("Favorites", image: "star")
    }
    
}

You can also scale both text and icon simultaneously:

struct ContentView: View {

    var body: some View {
        Label("Profile", systemImage: "person.circle")
            .font(.headline)
    }
    
}

Controlling Display Style

To modify the display style, use the labelStyle modifier:

struct ContentView: View {
    
    var body: some View {
        Label("Favorites", systemImage: "star")
            .labelStyle(.iconOnly)
        
        Label("Favorites", systemImage: "star")
            .labelStyle(.titleOnly)
        
        Label("Favorites", systemImage: "star")
            .labelStyle(.titleAndIcon)
    }
    
}

You can also create custom views for the label’s text and icon:

struct ContentView: View {
    
    var body: some View {
        Label {
            Text("Some text")
                .background(.red)
        } icon: {
            Circle()
                .fill(.purple)
                .frame(height: 80)
        }
    }
    
}