Intro to UIFontPickerViewController

A number of new font-management APIs were announced at WWDC 2019, including a standard system font picker for iOS and Catalyst apps (finally!). The session Font Management and Text Scaling covers the new APIs in detail; however, the sample code only exists on the slides and the documentation is currently very sparse. I thought it might be helpful to write out the sample code in a blog post, along with a little explanation.

UIFontPickerViewController is a customizable system font picker that, by default, has the following configuration:

  • displays all system fonts (including any fonts you include in your app bundle and that are specific to your app only)
  • shows only font families and not individual faces
  • uses a WYSIWYG presentation

To change these defaults, you can create a configuration object, initialize the font picker, and present it like so:

let config = UIFontPickerViewController.Configuration()
config.includeFaces = true
let fontPickerViewController = UIFontPickerViewController(configuration: config)
fontPickerViewController.delegate = self
self.present(fontPickerViewController, animated: true)

To display all font names using the system font, set displayUsingSystemFont to true.

You can also filter the font list by supplying an array of symbolic traits. For example, to display only monospaced fonts, you would do something like this:

let traits = UIFontDescriptor.SymbolicTraits(arrayLiteral: [.traitMonoSpace])
config.filteredTraits = traits

There are two delegate methods that allow you to control what happens after a user chooses a font or cancels font selection.

extension MyCustomViewController: UIFontPickerViewControllerDelegate {
    func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) {
        guard let fontDescriptor = viewController.selectedFontDescriptor else { return }
        let font = UIFont(descriptor: fontDescriptor, size: 48.0)
        textView.font = font
    }

    func fontPickerViewControllerDidCancel(_ viewController: UIFontPickerViewController) {
        print("User selected cancel.")
    }
}

Finally, if you want to display user-installed fonts, you need to add an entitlement to your app. In Xcode 11, go to your project settings, tap “Signing and Capabilities,” and add a new capability called “Fonts.” Under the Fonts entitlement are two options next to “Privileges.” Check the box by “Use Installed Fonts” to indicate that you want your app to read fonts that were installed by other apps.