How to change SwiftUI Font Width
Table of Contents
In iOS 16, Apple introduces three new width styles to the SF font family.
- Compressed
- Condensed
- Expanded
There are two ways to set font width in SwiftUI.
Set Font Width in SwiftUI
In Xcode 14.1, we got width(_:)
modifier that lets us set a font width.
In this example, we set the expanded
width to the large title style font. And set the compressed
width to the body style font.
VStack {
Text("Alphabet")
.font(
.largeTitle.width(.expanded)
)
Text("The quick brown fox jumps over the lazy dog")
.font(
.body.width(.compressed)
)
}
This new modifier aligns well with other modifiers like weight(_:)
.
And the best part about this new API is it is backward compatible with iOS 16!
You can easily support sarunw.com by checking out this sponsor.
Debug 10x faster with Proxyman: Your ultimate tool to capture HTTPs requests/ responses, natively built for your iPhone and macOS. Special deal for Black Friday: Get 30% off for all Proxyman licenses with code “BLACKFRIDAY2024”.
Set Font Width of the text in a view
SwiftUI has modifiers to modify text in the view, such as fontWeight(_:)
and font(_:)
. With the introduction of new width(_:)
modifier, Apple also introduce the fontWidth(_:)
modifier to align with current API set.
fontWidth(_:)
can set the font width of the text in the view.
In this example, we set font width to expanded
for every text in the VStack
.
VStack {
Text("Large Title")
.font(.largeTitle)
Text("Title 1")
.font(.title)
Text("Title 2")
.font(.title2)
Text("Title 3")
.font(.title3)
Text("Body")
.font(.body)
Text("Callout")
.font(.callout)
Text("Footnote")
.font(.footnote)
Text("Caption 1")
.font(.caption)
Text("Caption 2")
.font(.caption2)
}
.fontWidth(.expanded)
The modifier also backported to iOS 16.
Read more article about SwiftUI, Font, iOS 16, or see all available topic
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.
Become a patron Buy me a coffee Tweet ShareHow to create Rounded Corners View in SwiftUI
There are many ways to create a rounded corners button in SwiftUI. Let's learn how to do it.
How to add Keyboard Shortcuts in SwiftUI
You can easily add keyboard shortcuts to Mac, iPhone, and iPad with the keyboardShortcut modifier.