Dynamic Types iOS Tutorial

With Dynamic Types the user can specify the preferred text size in the Settings app of the device. Modern applications are expected to adjust text to the preferred size. Instead of setting the font size explicitly in the code, you can make use of the preferred font for a given text syle. In this tutorial some labels will be created, which will respond to the preferred text size. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSDynamicTypesTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag 6 labels to the main view. Give each label an unique text. Select all labels and select the Embed in stack view button on the bottom-right of the Interface Builder.

The stack view is a container view which will embed all containing items and manage the layout of its contents. Select the stack view and go to the Attribute Inspector. In the Stack view section select the following properties.

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible.Ctrl and drag from the Headline Label to the ViewController class  and create the following Outlet.

Repeat this step for the remaining Labels, the outlets should look like this in the ViewController class.

@IBOutlet weak var headlineLabel: UILabel!
@IBOutlet weak var headlineLabel:UILabel!
@IBOutlet weak var subheadlineLabel:UILabel!
@IBOutlet weak var bodyLabel:UILabel!
@IBOutlet weak var footnoteLabel:UILabel!
@IBOutlet weak var caption1Label:UILabel!
@IBOutlet weak var caption2Label:UILabel!

A helper method will be used to change the preffered fonts for the labels. Add the updateFonts method.

func updateFonts() {
    headlineLabel.font = UIFont.preferredFont(forTextStyle: .headline)
    subheadlineLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
    bodyLabel.font = UIFont.preferredFont(forTextStyle: .body)
    footnoteLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
    caption1Label.font = UIFont.preferredFont(forTextStyle: .caption1)
    caption2Label.font = UIFont.preferredFont(forTextStyle: .caption2)

These are the six preset styles. When the view appears the helper method will be called. Implement the viewDidAppear method.

override func viewDidAppear(_ animated: Bool) {

Build and Run the project, the labels are styled according to the preffered font.

Stop the Project, go to the Settings App in the iOS Simulator and select General -> Accessibility -> Larger Text. Drag the Slider to the right to increase the preferred font to the largest text. Build and Run the project again. The preferred font size of the Labels is now set to the largest font.

You can download the source code of the IOSDynamicTypesTutorial at the ioscreator repository on Github.