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.
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.
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)
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!