Tuesday, 26 April 2016

3D touch(Peek and Pop)

With the new latest iOS 9 update now we can use the 3D touch that can provide more flexibility to a user. One of them is the peek and pop feature to view the preview of the controller before opening it. Today we will learn how to implement it in our iOS apps. 

Before beginning let us first understand what is peek and pop.
   Peek – To display the preview is called as peek.
   Pop – Navigation to the view that is currently shown as preview is  called as pop.


Let us first create a simple view controller project with the navigation controller. Now create a another controller that will show as a preview.
Now to implement peek and  pop, first step is to register the view that will be source. In our demo we will use table view as a source view.

if traitCollection.forceTouchCapability == UIForceTouchCapability.Available {
            registerForPreviewingWithDelegate(self, sourceView: self.tblPeekPop 
}

Note – Before registering source view make sure that device supports the 3D touch.
 
Now the next step is to conforms the UIViewControllerPreviewingDelegate. Let’s implement the delegate that are required for peek and pop.

func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {

        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
        let objPreviewView = storyboard.instantiateViewControllerWithIdentifier("PreviewViewController") as? PreviewViewController 
      /*objPreviewView!.preferredContentSize = CGSize(width: 0.0, height:180.0) */
      return objPreviewView
}    

In the above delegate method create a view controller that will show as a peek view. Here we can set the content size of the preview controller that will display the preview view of that height.

After preview when use force touch on the preview view then we have to navigate it to the view controller to display it in full screen.(Pop)

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

Here we will show the view controller that we have created to push in the navigation. Now user will move to the next view controller.

That’s all we have successfully integrated it.

Here is sample project with all the code of the above tutorial.

If you face any issue or have any suggestions, please leave your comment.








No comments:

Post a Comment