Using Dynamic Type in iOS iOS 08.05.2020

Some people prefer more compact interfaces so they can see more information at once. Others might want to be able to easily see information at a glance, or perhaps they have poor eyesight. In short: People have different needs. Good developers strive to make apps that meet those needs.

Dynamic Type is a technology that helps realize this goal by providing specifically designed text styles that are optimized for legibility. Apple introduced dynamic type in iOS 7 to allow users to specify their preferred text size in the Settings app. Users can select one of seven preferred text sizes from within Apple’s Settings application (plus a few additional larger sizes from within the Accessibility section), and apps that support Dynamic Type will have their fonts scaled appropriately.

When a font is requested for a given text style, the system will consider the user’s preferred text size in association with the text style to return an appropriately configured font.

There are a variety of text styles ranging from the smallest Caption 2 to the largest Large Title to suit your layout.

ios_dynamic_type.png

Open Main.storyboard. Let’s update a label to use text styles instead of fixed fonts. Now let’s change the simulator’s preferred font size. You do this through the Settings application. Choose Accessibility, then Display & Text Size, and then Larger Text.

By default, the preset text styles font size are set when the app launches, meaning if the user change the settings font size in the mid of using your app, they need to quit and relaunch your app to see the updated text size.

To support auto text size adjustment (ie. the app text size changes automatically when user adjust the text size in Settings app, without having to relaunch your app), simply check the Automatically Adjusts Font checkbox in the Attribute inspector.

Open Main.storyboard and select all your label. Open the attributes inspector, and check the Automatically Adjusts Font checkbox. This will set the corresponding adjustsFontForContentSizeCategory property on each label to true.

To support dynamic type programmatically, we can use the preferredFont(forTextStyle:) method of UIFont.

label.font = UIFont.preferredFont(forTextStyle: .largeTitle)
label.adjustsFontForContentSizeCategory = true

Scaling custom fonts

As the preset text styles use System Font, what if we want to use a custom font, say Avenir Next and support dynamic type at the same time?

In iOS 11, Apple has introduced UIFontMetrics class to let us support dynamic type on custom font easily.

To support dynamic type on custom font, we can use the UIFontMetrics to bind a certain text style for a label font like this

let font = UIFont(name: "AvenirNext-Regular", size: 18.0)!
label.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: customFont)

Useful links