Dynamic Type Fonts

Overview

Using dynamic type font size, user can set preferred text size from device settings and user will see effect on app’s font. It’s a good feature for making apps accessible to users. Rather than setting the font size from code, you can set preferred font for given text style.

There are two ways for setting dynamic type. First, you can do it from the storyboard and second, using code when setting up a view.

Using StoryBoard:

You can make dynamic type by checking the ‘Automatically Adjusts Font’. When user checks ‘Automatically Adjust Font’ the font size changes as soon as user changes preferred size.
The ‘Automatically Adjust Font’ in attribute inspector applies only to only text styles. There is no effect on custom font.

storyboard

Using Code:

The UIFont API provides preferedFontforTextStyle method that returns preferred font for given text style. There are 10 types of default built-in text style. Here is the list of all of our text styles along with their font size at the default text size.

List of Text Style with default sizes:

  1. title1: System 28pt
  2. title2: System 22pt
  3. title3: System 20pt
  4. headline: System 17pt
  5. body: System 17pt
  6. callout: System 16pt
  7. subhead: System 15pt
  8. footnote: System 13pt
  9. caption1: System 12pt
  10. caption2: System 11pt

I used some label in my tutorial and below is the few lines of code for making them dynamic type.

Apple added adjustsFontForContentSizeCategory in iOS 10. When it is true the font size updates as per preferred font size.

Custom font with Dynamic Type

I mentioned above that the ‘Automatically Adjust Font’ does not apply on custom font so for custom font, Apple introduced font metric class in iOS 11 that makes it easy. First you get the font metrics for particular text style and then you can scale your custom font using font metrics.

First you get the font metrics for the .title1 text style and using scaledFont(for method you get the font as per the preferred text size.

Another one is UIFontMetrics.default.scaledFont(for method that returns font as per preferred text size but by default it takes .body text style.

Run the project and you can show that the labels are styled according to preferred text size. Here are the two screenshots for different preferred text sizes.

font-screenshot

font-screenshot

mm

Harshad Nayak iOS Developer

I am Harshad Nayak, iOS Developer at Yudiz Solutions Pvt. Ltd. - leading iPhone App development company. I am a tech savvy Guy. Passionate about Singing, Cricket and Chess.

Comments are closed.

Top