Episode #262

Peek and Pop

11 minutes
Published on April 6, 2017

This video is only available to subscribers. Get access to this video and 584 others.

Conrad Stoll shows us how to implement Peek and Pop using 3D Touch on supported devices. We learn how to do it in code versus the storyboard, as well as how to customize the display and presentation of the previewed view controller.

This week's episode was authored by Conrad Stoll.

Episode Links

Register for Previewing

    registerForPreviewing(with: self, sourceView: tableView)

Previewing Delegate View Controller for Location

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {        
        if let indexPath = tableView.indexPathForRow(at: location) {
            previewingContext.sourceRect = tableView.rectForRow(at: indexPath)

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let optionsViewController = storyboard.instantiateViewController(withIdentifier: "OptionsViewController") as! OptionsViewController
            let item = collection.items[indexPath.row]

            optionsViewController.delegate = self
            optionsViewController.item = item

            presentedOptionsController = optionsViewController

            return optionsViewController
        }

        return nil
    }

Previewing Delegate Commit View Controller

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
        self.navigationController?.pushViewController(viewControllerToCommit, animated: true)

        if let vc = viewControllerToCommit as? OptionsViewController {
            vc.updateToCommittedUI()
        }
    }

Customizing Content Size on Previewed View Controller

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        let labelHeight = label.frame.size.height
        let containerHeight = labelHeight + 40.0

        self.preferredContentSize = CGSize(width: self.view.frame.size.height, height: containerHeight)
    }

This episode uses Ios 10.2, Xcode 8.2.