Text Kit Tutorial: Getting Started

In this tutorial, you’ll learn how to use Text Kit in your iOS app to layout your text and create different visual styles. By Bill Morefield.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Reviving Dynamic Type

To correct the issue with dynamic type, your code should update the fonts used by the attributed string containing the text of the note when the content size change notification occurs.

Add the following function to the SyntaxHighlightTextStorage class:

func update() {
  let bodyFont = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .body)]
  addAttributes(bodyFont, range: NSMakeRange(0, length))
    
  createHighlightPatterns()
  applyStylesToRange(searchRange: NSMakeRange(0, length))
}

The method above applies the body text style to the entire string, re-creates the highlight patterns based on the new font configuration and then re-applies the highlighting styles.

Finally, open NoteEditorViewController.swift and add this line to viewDidLayoutSubviews() to perform the update:

textStorage.update()

Build and run. Change your text size preferences, and the text should adjust accordingly:

Text sizes comparison

Where to Go From Here?

Hopefully, this Text Kit tutorial has helped you understand the features of the library you'll no doubt find useful in practically every app that you write. You've implemented dynamic type support, learned to respond to changes in text sizes within your app, used exclusion paths, and dynamically applied styles to text.

You can download the completed version of the project using the Download Materials button at the top or bottom of this tutorial to view the final project.

If you'd like to learn more about Dynamic Type, check out our book iOS 11 By Tutorials. The book has a chapter on using Dynamic Type in your app.

We hope you enjoyed this tutorial. If you have any questions or comments please join the forum discussion below!