Attributed Strings Tutorial in iOS8 with Swift

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 label's text. This tutorial is built with iOS8.1 and Xcode 6.1.

Update: Apr 22, 2015. This tutorial is updated for Swift 1.2 and Xcode 6.3.

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftAttributedStringsTutorial 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 View Controller. Change the background color of the main view to light-gray.Select the label and select the "Resolve Auto Layout Issues" button at the bottom-right(3rd button) and select Add Missing Constraints.

The Storyboard should look like this.

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" as NSString
    var attributedString = NSMutableAttributedString(string: string as String)
    // 2
    let firstAttributes = [NSForegroundColorAttributeName: UIColor.blueColor(), NSBackgroundColorAttributeName: UIColor.yellowColor(), NSUnderlineStyleAttributeName: 1]
    let secondAttributes = [NSForegroundColorAttributeName: UIColor.redColor(), NSBackgroundColorAttributeName: UIColor.blueColor(), NSStrikethroughStyleAttributeName: 1]
    let thirdAttributes = [NSForegroundColorAttributeName: UIColor.greenColor(), NSBackgroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(40)]
    // 3
    attributedString.addAttributes(firstAttributes, range: string.rangeOfString("Testing"))
    attributedString.addAttributes(secondAttributes, range: string.rangeOfString("Attributed"))
    attributedString.addAttributes(thirdAttributes, range: string.rangeOfString("Strings"))
    // 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 IOS8SwiftAttributedStringsTutorial at the ioscreator repository on Github.