Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.


#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:

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:

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:

func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
  showViewController(viewControllerToCommit, sender: self)