Styling measurement unit fonts in SwiftUI
By default, SwiftUI's Text view renders formatted measurements as a uniform string and applies the same font and style to both the value and the unit. In some situations we might want to style the unit differently from the value to make it less dominant, for example. We can do this using the AttributedString API.
We can build a reusable Text initializer that targets only the unit component of a formatted measurement and applies a distinct font.
extension Text {
init<T: Dimension>(
_ measurement: Measurement<T>,
format: Measurement<T>.FormatStyle,
unitFont: Font
) {
var str = format.attributed.format(measurement)
str = str.transformingAttributes(
\.measurement, \.font
) { metadata, font in
if metadata.value == .unit {
font.value = unitFont
}
}
self.init(str)
}
}
The transformingAttributes(_:_:_:) method gives us simultaneous access to both the semantic measurement attributes and the underlying font attributes, so we can update the font for the unit component without affecting the value.
With this initializer in place, we can render a measurement with the unit styled separately from the value.
struct ExampleDistanceView: View {
let distance = Measurement(value: 5, unit: UnitLength.kilometers)
var body: some View {
Text(
distance,
format: .measurement(width: .abbreviated),
unitFont: .caption
)
.font(.headline)
}
}
Internal attributes inside the AttributedString take priority over outer text modifiers, so we can style the measurement value using any standard text modifier applied to the Text view directly.
When the unit uses a smaller font size than the value, the whitespace between them may look visually off. We can remove it by passing narrow to the format width parameter instead of abbreviated.
Text(
distance,
format: .measurement(width: .narrow),
unitFont: .caption
)
.font(.headline)
If you are looking to build a strong foundation in SwiftUI, my book SwiftUI Fundamentals takes a deep dive into the framework's core principles and APIs to help you understand how it works under the hood and how to use it effectively in your projects. And my new book The SwiftUI Way helps you adopt recommended patterns, avoid common pitfalls, and use SwiftUI's native tools appropriately to work with the framework rather than against it.
For more resources on Swift and SwiftUI, check out my other books and book bundles.
I’m currently running a WWDC 2026 promotion with 30% off my books, plus additional savings when purchased as a bundle. Visit the books page to learn more.



