Buddybuild is a CI, CD and user feedback platform built for mobile development teams - sign up for free and start building better apps!

Topics

#309: UIFontMetrics πŸ“

Topics

Happy WWDC 2017! Today we're beginning our look at the incredibly large list of updates and improvements announced this week with UIFontMetrics. Let's jump in.

We'll start with the problem we're trying to solve. It's all about Dynamic Type.

Our users can adjust their preferred Dynamic Type value in Settings.app to display the text in our apps larger and more prominently.

This works great when we want to use the system default font, since we can simply write some code like this:

let font = UIFont.preferredFont(forTextStyle: .headline)

This will return a UIFont that is appropriate for the given text style, adjusted by size and weight to match the user's Dynamic Type setting.

But what about custom fonts? In the past this was a bit cumbersome and we often had to resort to ugly hacks.

Enter UIFontMetrics! We can use this new type in iOS 11 to ask the system to scale our font size for us:

let headlineMetrics = UIFontMetrics(forTextStyle: .headline)
let fontBeforeScaling = UIFont(name: "Chicago", size: 16.0)
let font = headlineMetrics.scaledFont(for: fontBeforeScaling)

Neat!

There's always one more fun trick tucked away in UIFontMetrics, and that is scaling arbitrary values. This is great for helping us size our UI elements (for example buttons or headers) to accomodate dynamically sized fonts that live inside:

let headlineMetrics = UIFontMetrics(forTextStyle: .headline)
let heightBeforeScaling = 44.0
let height = headlineMetrics.scaledValue(forValue: heightBeforeScaling)

No more large text in tiny buttons. Very cool!