---
title: "#309: UIFontMetrics 📐"
url: https://littlebitesofcocoa.com/309-uifontmetrics
author: Jake Marsh
published: 2017-06-06
topics: ["UIKit","Text"]
description: "Happy WWDC 2017! Today we're beginning our look at the incredibly large list of updates and improvements announced this week with UIFontMetrics."
---

# #309: UIFontMetrics 📐

By Jake Marsh, June 6, 2017. HTML: https://littlebitesofcocoa.com/309-uifontmetrics

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](https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/).

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:

``` swift
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:

``` swift
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:

``` swift
let headlineMetrics = UIFontMetrics(forTextStyle: .headline)
let heightBeforeScaling = 44.0
let height = headlineMetrics.scaledValue(forValue: heightBeforeScaling)
```

No more large text in tiny buttons. Very cool!

<p></p>
