BLACK FRIDAY: Save 50% on all my books and bundles! >>

How to give label icons a fixed width

Paul Hudson    @twostraws   

Updated for Xcode 16.4

New in iOS 26

SwiftUI's Label view shows an icon and text side by side, but if the icons are varying widths then the position of your text will vary and it looks a little scruffy.

We can fix this using the labelReservedIconWidth() modifier, which reserves a fixed amount of space for the icon in your label, allowing you to align them neatly:

VStack {
    Button("Example", systemImage: "plus") { }
    Button("Example", systemImage: "envelope.front") { }
}
.font(.largeTitle)
.labelReservedIconWidth(50)

Download this as an Xcode project

That ensures each icon takes up a constant 50 points of width, which in turn means that the label titles will be aligned correctly.

Important: This modifier does not currently adapt to Dynamic Type automatically, so hard coding a specific number isn't going to scale well.

I hope this gets addressed by Apple before release so that the modifier does the right thing automatically, but in the meantime we need to use @ScaledMetric like this:

struct ContentView: View {
    @ScaledMetric private var iconWidth = 50.0

    var body: some View {
        VStack {
            Button("Example", systemImage: "plus") { }
            Button("Example", systemImage: "envelope.front") { }
        }
        .font(.largeTitle)
        .labelReservedIconWidth(iconWidth)
    }
}

Download this as an Xcode project

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new, fully customizable Paywall Editor allow you to remotely change your paywall view without any code changes or app updates.

Learn more here

Similar solutions…

BUY OUR BOOKS
Buy Everything but the Code Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Interview Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 1.0/5

 
Unknown user

You are not logged in

Log in or create account