Topics

#54: Dynamic Type Basics πŸ“„

Topics

Dynamic Type is a system introduced back in iOS 7 with the intention of unifying and simplifying how users change their preference for how big text should be on the screen. While the user choice is simple, under the hood Dynamic Type earns its name by dynamically adjusting things such as spacing between characters and character weights to make text as readable as possible.

Let’s take a look at how to add simple Dynamic Type support.

Text Styles

The main way you interact with Dynamic Type is through the built-in set of text styles. As of iOS 9, 9 styles are available to choose from:

  • UIFontTextStyleTitle1
  • UIFontTextStyleTitle2
  • UIFontTextStyleTitle3
  • UIFontTextStyleHeadline
  • UIFontTextStyleSubheadline
  • UIFontTextStyleBody
  • UIFontTextStyleFootnote
  • UIFontTextStyleCaption1
  • UIFontTextStyleCaption2

Retrieving Fonts

If you’re using the system font, all you need is:

UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)

For custom fonts, you’ll need to grab a font descriptor first, then create the UIFont manually:

let fontSize = UIFontDescriptor
  .preferredFontDescriptorWithTextStyle(UIFontTextStyleHeadline)
  .pointSize

let font = UIFont(name: "Avenir Next", size: fontSize)

Lastly, you'll want to update your UI when the user changes their preferences in Settings.app. Observe this notification and trigger a re-layout when it occurs:

NSNotificationCenter.defaultCenter().addObserver(self,
  selector: "preferredContentSizeChanged:",
  name: UIContentSizeCategoryDidChangeNotification, object: nil)