---
title: "#144: Drawing Multiline Strings 📖"
url: https://littlebitesofcocoa.com/144-drawing-multiline-strings
author: Jake Marsh
date: 2015-12-10
published: 2015-12-10
topics: ["Text","Core Graphics","UIKit"]
description: "Let's draw some strings! There's plenty of text-drawing capabilities in iOS and OS X, with full frameworks like Text Kit (or the lower-level Core Text)..."
---

# #144: Drawing Multiline Strings 📖

By Jake Marsh, December 10, 2015. HTML: https://littlebitesofcocoa.com/144-drawing-multiline-strings

Let's draw some _strings_! There's plenty of text-drawing capabilities in **iOS** and **OS X**, with full frameworks like **Text Kit** (or the lower-level **Core Text**) dedicated to the task. Today, we'll start looking at these capabilities by using **Core Graphics** and **UIKit** to draw a _multiline string_.

Sometimes we need to draw text ourselves, “manually”. This can be helpful when optimizing for scrolling performance, or when complete customization is necessary. 

First we'll need a view to draw into, we'll make a new **UIView**, and override `drawRect`.

Next, we'll start implementing our `drawRect` **function** with a few **variables**. We'll choose a font, then setup a **paragraph style** to make our text multiline, with some tall lines.

We'll also setup some **drawing options** to tell the system we want multiline text:

``` swift
let textFont = UIFont(name: "Avenir Next", size: 17.0)!
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.2
paragraphStyle.lineBreakMode = .ByWordWrapping

let drawingOptions: NSStringDrawingOptions = [
  .UsesLineFragmentOrigin, .UsesFontLeading]
```

We'll save these off into a `textAttributes` **dictionary**. Next, we'll need to figure out what **rectangle** we'll be drawing our **text** into.

We'll use the `boundingRectWithSize` **function** to find out how tall it will be when constrained to the **width** of our **view**:

``` swift
let textRect = (text as NSString)
  .boundingRectWithSize(
    CGSizeMake(bounds.size.width, CGFloat.max),
    options: drawingOptions,
    attributes: textAttributes,
    context: nil)
```

Then we'll just pass that calculated **textRect** into a call to **drawWithRect**:

``` swift
(text as NSString).drawWithRect(textRect,
  options: drawingOptions,
  attributes: textAttributes,
  context: nil)
```

<img src='https://media.littlebitesofcocoa.com/bite-assets/144-drawing-multiline-strings-final.png' style='max-width: 131px;' />
