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 8 and built for iOS 10.

Open Xcode and create a new Single View Application

Choose Next. For product name, use IOS10AttributedStringsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and drag a Label from the Object Library to the main View. Select the Align button from the Auto Layout buttons on the bottom-right of the Storyboard and fill in the following value. Select "Add 1 Constraint".

Select the Pin button from the Auto Layout buttons on the bottom-right of the Storyboard and fill in the following value. Select "Add 1 Constraint".

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() {
    super.viewDidLoad()
        
    // 1
    let string = "Testing Attributed Strings"
    let attributedString = NSMutableAttributedString(string: string)
        
    // 2
    let firstAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.blue, NSBackgroundColorAttributeName: UIColor.yellow, NSUnderlineStyleAttributeName: 1]
    let secondAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.red, NSBackgroundColorAttributeName: UIColor.blue, NSStrikethroughStyleAttributeName: 1]
    let thirdAttributes:[String:Any] = [NSForegroundColorAttributeName: UIColor.green, NSBackgroundColorAttributeName: UIColor.black, NSFontAttributeName: 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 IOS10AttributedStringsTutorial at the ioscreator repository on Github.