

How to change SwiftUI Font Width
source link: https://sarunw.com/posts/swiftui-font-width/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

Compressed, Condensed, and Expanded font width.
Unfortunately, SwiftUI has no API to access this feature. We have learn this hard truth in SF Font Expanded, Condensed, and Compressed: Three New font width styles in iOS 16.
In Xcode 14.1 (Currently in beta 3), SwiftUI finally got new APIs to set the font width.
There are two ways to set font width in SwiftUI.
You can easily support sarunw.com by checking out this sponsor.
Sponsor sarunw.com and reach thousands of iOS developers.
Set Font Width in SwiftUI
In Xcode 14.1, we got width(_:)
modifier that lets us set a font width to the font.
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)
)
}

Use .width(_:) modifier to set the font width.
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!

The width(_:) modifier is backward compatible with iOS 16.
You can easily support sarunw.com by checking out this sponsor.
Sponsor sarunw.com and reach thousands of iOS developers.
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)

Use fontWidth(_:) modifier to set the font width of the text in the view.
The modifier also backported to iOS 16.

Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK