Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale system font in SwiftUI to support Dynamic Type?

In UIKit, I can change a UILabel's font size like this to support dynamic type using the system font:

UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: 16))

Am I mistaken or is there no way to do such thing in SwiftUI? Can I only use the default font styles .title, etc. if I want to use the system font but also support Dynamic Type?

This solution from HackingWithSwift seems to only work with custom fonts, right?

Thanks in advance for any suggestions!

like image 680
sinalco12 Avatar asked Jan 16 '20 13:01

sinalco12


People also ask

How do I set dynamic font size in SwiftUI?

SwiftUI comes with support for all of Dynamic Type's font sizes, all set using the . font() modifier. However, if you ask for a specific font and size, you'll find your text no longer scales up or down automatically according to the user's Dynamic Type settings – it remains fixed.

How do you support dynamic type?

To add support for Dynamic Type in your app, you use text styles. A text style describes the use of the text, such as headline or body or title1 , and lets the system know how best to adjust its size. You can configure text styles in either Interface Builder or your source code.

What is dynamic font sizing?

The Dynamic Type feature allows users to choose the size of textual content displayed on the screen. It helps users who need larger text for better readability. It also accommodates those who can read smaller text, allowing more information to appear on the screen.


Video Answer


1 Answers

The following approach works (tested with Xcode 11.2.1 / iOS 13.2.2)

var body: some View {
    Text("Hello, World!") // direct text .font
        .font(Font.system(size: UIFontMetrics.default.scaledValue(for: 16)))
}

as well as for view-based modifier

VStack {
    Text("Hello, World!")
}
.font(Font.system(size: UIFontMetrics.default.scaledValue(for: 16)))
like image 173
Asperi Avatar answered Sep 22 '22 15:09

Asperi