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.
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:
- title1: System 28pt
- title2: System 22pt
- title3: System 20pt
- headline: System 17pt
- body: System 17pt
- callout: System 16pt
- subhead: System 15pt
- footnote: System 13pt
- caption1: System 12pt
- caption2: System 11pt
I used some label in my tutorial and below is the few lines of code for making them dynamic type.
lblTitle3.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) lblBody.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body) lblCaption1.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1) lblCaption2.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2) lblSubhead.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline) lblFootnote.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote)
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.
lblCustomFont1.font = UIFontMetrics(forTextStyle: .title1).scaledFont(for: UIFont(name: "Helvetica", size: 10)!)
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.
lblCustomFont2.font = UIFontMetrics.default.scaledFont(for: UIFont(name: "Helvetica", size: 15)!)
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.