Attributed Strings iOS Tutorial

Attributed Strings assigns different kind of attributes to text. It is possible to assign multiple attributes at once to a (part) of text. In this tutorial we will assign a set of attributes to each word of the text inside a label. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSAttributedStringsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag a Label from the Object Library to the main View. Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Label to the ViewController class  and create the following Outlet.

Go to the ViewController.swift file and change the viewDidLoad method to

override func viewDidLoad() {

    // 1
    let string = "Testing Attributed Strings"
    let attributedString = NSMutableAttributedString(string: string)

    // 2
    let firstAttributes: [NSAttributedString.Key: Any] = [
        .backgroundColor: UIColor.yellow,
        .underlineStyle: 1]
    let secondAttributes: [NSAttributedString.Key: Any] = [
        .strikethroughStyle: 1]
    let thirdAttributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 40)]

    // 3
    attributedString.addAttributes(firstAttributes, range: NSRange(location: 0, length: 8))
    attributedString.addAttributes(secondAttributes, range: NSRange(location: 8, length: 11))
    attributedString.addAttributes(thirdAttributes, range: NSRange(location: 19, length: 7))

    // 4
    attributedLabel.attributedText = attributedString
  1. a regular string is created and this is loaded into a mutable attributed string.

  2. three different dictionaries are created containing attributed key/values.

  3. The attributes are added to the substrings of the attributes strings.

  4. finally, the attributed string is assigned to the Label.

Build and Run the project, A attributed string will be displayed.

You can download the source code of the IOSAttributedStringsTutorial at the ioscreator repository on Github.