Font modifiers in SwiftUI
We are all familiar with view modifiers in SwiftUI, such as font()
, background()
, frame()
, etc. We use them all the time to style and customize views in our apps. They are methods defined on the View
type that return a different version of the original view. I previously wrote about text modifiers, which are methods applied directly to Text
, returning a modified Text
, that can be used inside text interpolation. In this post I'd like to explore font modifiers, which work similarly to view and text modifiers but are applied to the Font
type, returning a modified font.
Here is an example of font modifiers in action. We apply bold()
, monospaced()
and smallCaps()
to the largeTitle
font to customize the way it looks.
Text("Hello, world!")
.font(
.largeTitle
.bold()
.monospaced()
.smallCaps()
)
We can view the full list of font modifiers in SwiftUI Font documentation in the "Styling a font" section. We can see that they are not exactly the same as modifiers available on the Text type or methods for styling text on the View
type.
For example, there is a font modifier for customizing leading, which lets us adjust the line spacing of a font and takes a Font.Leading enum as an argument. This modifier can't be applied to a Text
or any other view, only to a Font
.
VStack(spacing: 20) {
Text(exampleText)
.font(
.largeTitle
.leading(.tight)
)
Text(exampleText)
.font(
.largeTitle
.leading(.loose)
)
}
Font modifiers are a great way to manage typography in SwiftUI, letting us style text directly at the font level. Using these modifiers thoughtfully can help us create a polished look that improves our app’s user experience.
If you have older iOS apps and want to enhance them with modern SwiftUI features, check out my book Integrating SwiftUI into UIKit Apps. It provides detailed guidance on gradually adopting SwiftUI in your UIKit projects. Additionally, if you're eager to enhance your Swift programming skills, my latest book Swift Gems offers over a hundred advanced tips and techniques, including optimizing collections, handling strings, mastering asynchronous programming, and debugging, to take your Swift code to the next level.
I’m currently running a Black Friday 2024 promotion with 30% off my books, plus additional savings when purchased as a bundle. Visit the books page to learn more.