---
title: "#80: View Controller Previews 👓"
url: https://littlebitesofcocoa.com/80-view-controller-previews
author: Jake Marsh
published: 2015-09-11
topics: ["UIKit","3D Touch"]
description: "View Controller Previews are another iOS SDK feature announced with 3D Touch on the iPhone 6S and iPhone 6S Plus."
---

# #80: View Controller Previews 👓

By Jake Marsh, September 11, 2015. HTML: https://littlebitesofcocoa.com/80-view-controller-previews

_View Controller Previews_ are another iOS SDK feature announced with **3D Touch** on the **iPhone 6S** and **iPhone 6S Plus**. They allow users to easily "peek" into a piece of content by pressing lightly, then pressing a little more firmly to actually open it. Let's take a look.

First we'll make sure **3D Touch** is available, and register for previewing:

``` swift
if traitCollection.forceTouchCapability == .Available {
  registerForPreviewingWithDelegate(self, sourceView: view)
} else { print("3D Touch is not available on this device.") }
```

Then we need to conform to `UIViewControllerPreviewingDelegate`:

``` swift
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  guard let indexPath = tableView.indexPathForRowAtPoint(location),
            cell = tableView.cellForRowAtIndexPath(indexPath) else { return nil }

  let vc = DetailViewController(spaceship: spaceships[indexPath.row])

  vc.preferredContentSize = CGSize(width: 0.0, height: 200.0)
  previewingContext.sourceRect = cell.frame

  return detailViewController
}
```

In the first **function** we'll need to return a fully configured **UIViewController** that will serve as the preview. We're coming from a **table view controller**, so we'll use the passed in **location** to grab the cell that was pressed, and configure our preview **view controller**.

We also set the **cell's** `frame` to be our `previewContext`'s `sourceRect`. This accomplishes "blurring out" all the other elements on the screen during the preview.

We finish things out by implementing the second **function**, called when the user decides to "pop" into the content. We could use a different **view controller** but we'll just reuse our existing preview one and show it:

``` swift
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
  showViewController(viewControllerToCommit, sender: self)
}
```
