Drawing text in a UIView with iOS and Swift

You can usually rely on UI classes such as UILabel to render text on a view. Sometimes however, you need to render text using the drawRect function of the UIView class. In the following example, we take an NSString, set some attributes and draw the text inside of a rectangle using the attributes.

To set up your project create a new file called MyView.swift.

The basic signature of the file should be:

import UIKit

class MyView: UIView {
  override func drawRect(rect: CGRect) {

  }
}

Now, go to your Main.storyboard and set the name under Identity and Type to MyView.swift.

You should be able to build and run your project without error. A blank view should be displayed as we haven't provided any actual drawing instructions yet.

Next we need to declare the string:

override func drawRect(rect: CGRect) {
  var s: NSString = "Whereof we cannot speak, thereof we must remain silent."
}

When drawing the string, we want to set the Color, Font, Font Size, Line Spacing and Obliqueness. To do so create a dictionary using the keys defined for NSAttributedString. You can find a list of these attribute names in the Apple Developer Documentation :

// set the text color to dark gray
let fieldColor: UIColor = UIColor.darkGrayColor()

// set the font to Helvetica Neue 18
let fieldFont = UIFont(name: "Helvetica Neue", size: 18)

// set the line spacing to 6
var paraStyle = NSMutableParagraphStyle()
paraStyle.lineSpacing = 6.0

// set the Obliqueness to 0.1
var skew = 0.1

var attributes: NSDictionary = [
  NSForegroundColorAttributeName: fieldColor,
  NSParagraphStyleAttributeName: paraStyle,
  NSObliquenessAttributeName: skew,
  NSFontAttributeName: fieldFont!
]

Finally we are ready to draw the text. We will do so inside of a rectangle that is 20 pixels from the left, 140 pixels from the top, 300 pixels wide and 48 pixels high.

s.drawInRect(CGRectMake(20.0, 140.0, 300.0, 48.0), withAttributes: attributes)

The completed drawRect function should now be:

override func drawRect(rect: CGRect) {

  var s: NSString = "Whereof we cannot speak, thereof we must remain silent."

  // set the text color to dark gray
  let fieldColor: UIColor = UIColor.darkGrayColor()

  // set the font to Helvetica Neue 18
  let fieldFont = UIFont(name: "Helvetica Neue", size: 18)

  // set the line spacing to 6
  var paraStyle = NSMutableParagraphStyle()
paraStyle.lineSpacing = 6.0

  // set the Obliqueness to 0.1
  var skew = 0.1

  var attributes: NSDictionary = [
    NSForegroundColorAttributeName: fieldColor,
    NSParagraphStyleAttributeName: paraStyle,
    NSObliquenessAttributeName: skew,
    NSFontAttributeName: fieldFont!
  ]

  s.drawInRect(CGRectMake(20.0, 140.0, 300.0, 48.0), withAttributes: attributes)

}

When you run and build the project you will see the text displayed in Helvetica Neue 18 oblique in dark gray. Additionally, the text is wrapped within the bounds of the specified rectangle with a 6 pixel line spacing.