3D Touch Peek and Pop Tutorial

published in iOS Development, Tutorials
by Piotr Przeliorz

With the release of the new model of phones: the iPhone 6s, Apple introduced 3D Touch. It's a functionality that allows the user to interact with the device using pressure. In the "3D Touch Peek and Pop Tutorial", I will show you how to use the Peek and Pop feature in iOS app development.

In our last article: 3D Touch Quick Actions Tutorial, Szymon described Quick Actions. Here you will learn how to implement the Peek and Pop feature, which can be found in applications like Mail as well as the App Store. This is a must read if you are an iOS app developer!

Getting started with Peek and Pop using 3D Touch

In the first part of the tutorial, you will create UIViewController‘s which you will later use to implement the Peek and Pop functionality. To create the application UI, use Storyboard.

The first obstacle will be to create two views and to combine the view components with ViewControllers using @IBOutlets.
3D Touch Peek and Pop

For the next step createstruct which will represent the object Restaurant:


struct Restaurant {
    var name: String
    var photo: UIImage
    var description: String
    var address: String
    
}

In the first UIViewController you create a table of objects of the type Restaurant, which will later be presented by UITableView:


         fileprivate var restaurants: [Restaurant] = {
        return [
            Restaurant(name: "Marina", photo: #imageLiteral(resourceName: "marina_restaurant"), description: Decriptions.Marina.rawValue, address: Addresses.Marina.rawValue),
            Restaurant(name: "Monopol", photo:  #imageLiteral(resourceName: "monopol_restaurant"), description: Decriptions.Monopol.rawValue, address: Addresses.Monopol.rawValue),
            Restaurant(name: "Campo", photo:#imageLiteral(resourceName: "campo_restaurant"), description: Decriptions.Campo.rawValue, address: Addresses.Campo.rawValue),
            ]
    }()

To display the objects in the Restaurants table, the next step is to implement the: UITableViewDelegate, UITableViewDataSource in the first UIViewController.


     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return restaurants.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.restaurantTableView.dequeueReusableCell(withIdentifier: RestaurantCell.identifier) as! RestaurantCell
        cell.configureCellView(withRestaurant: restaurants[indexPath.row])
        return cell
    }  

Then you get UIViewController as delegate and data source for TableView:


       restaurantTableView.delegate = self
       restaurantTableView.dataSource = self 

Now your iOS application should look as follows:

3D Touch Peek and Pop

How to implement 3D Touch Peek and Pop in Swift

After performing the previous steps you are ready to implement the Peek and Pop functionality in your iPhone app.

In this part of the tutorial you first need to extend the UIViewController to the UIViewControllerPreviewingDelegate protocol. This contains methods that will allow:
• a preview of the UIViewController containing detailed information about the object in the list
• access to an object in the list by pressing the button more firmly

Important: Before implementing the UIViewControllerPreviewingDelegate processes, check if your device supports 3D Touch functionality!


       guard traitCollection.forceTouchCapability == .available else { return }
       registerForPreviewing(with: self, sourceView: view) 

If the device supports force touch, register the UIViewController to allow it to show a preview (peek) and move on to the next UIViewController (pop).
After checking for 3D Touch support, extend the UIViewController to the UIViewControllerPreviewingDelegate:


extension RestaurantsViewController: UIViewControllerPreviewingDelegate {
}

Swift app development: method previewingContext

The first method you will implement is the method that is invoked when the user presses the source view (that is, the UIView managed by the UIViewController in which you currently find yourself).

The steps to be taken under this method are:


func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
	//1
        guard let indexPath = restaurantTableView?.indexPathForRow(at: location) else { return nil }
	//2
        guard let cell = restaurantTableView?.cellForRow(at: indexPath) else { return nil }

	//3
    previewingContext.sourceRect = cell.frame

	//4
        guard let restuarantDetailsViewController = storyboard?.instantiateViewController(withIdentifier: RestaurantDetailsViewController.identifier) as? RestaurantDetailsViewController else { return nil }
	//5
        let restaurant = restaurants[indexPath.row]

	//6
        restuarantDetailsViewController.restaurant = restaurant

	//7
        restuarantDetailsViewController.preferredContentSize = CGSize(width: 0, height: 500)
   
	//8
        return restuarantDetailsViewControlle
 }

Below is a description of the steps that need to be taken:

1. Create indexPath based on the coordinates of the place where the user clicked on the view (the place is represented by the CGPoint object and passed in the argument of the method).

2. Using a previously created indexPath, you can create a cell object presented by UITableView.

3. Specify the area that will be exposed (the rest of the screen will be slightly fuzzy, in this case, it’s the area of the selected cell).

4. Create a UIViewControlller that will display the details of the object presented in this view.

5. Create an object for a particular restaurant based on the previously obtained indexPath.

6. Pass the Restaurant object to the UIViewController, which will be able to view it after the view setup.

7. Specify the dimensions of the UIViewController preview.

8. Return the UIViewController objects that will be presented in the preview.

How did it go?

After you implement the previewingContext method, you should get the functionality outlined below:

3D Touch Peek and Pop

Develop iPhone app: almost done!

The second method from the UIViewControllerPreviewingDelegate, allows you to move on to the next UIViewController when the user presses hardest on the button. It needs to be implemented! This will be a lot faster:


    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
// 1
        show(viewControllerToCommit, sender: self)
    }

1. You present theUIViewController which is passed in the parameter of the method.

That’s it for the 3D Touch Peek and Pop Tutorial!

As a summary: thanks to 3D Touch you can significantly improve the user experience of your iPhone application. Remember that the functionality must be turned on:
Touch in Settings > General > Accessibility > 3D Touch
Check out the other possibilities 3D Touch offers in the documentation found on the Apple website.


You can find the source code on my GitHub.


Piotr Przeliorz

Regardless of complicated surname, Piotr believes in simple solutions. He loves to create, to modify, to make mistakes in iOS apps and to correct them. And, last but not least, to have fun with every single line of new code.

Popular posts

3D Touch Quick Actions Tutorial

3D Touch Quick Actions Tutorial

Did you know that the iPhone is able to detect different levels of touch depending on how hard you press? This is all thanks to 3D Touch! Check out how to add 3D Touch quick actions to your iOS apps.

Read more
BDD frameworks (part 3)

BDD frameworks (part 3)

In this series of articles, I am presenting selected BDD frameworks. In this part, I will talk about Spock – a unit testing framework.

Read more
BDD frameworks (part 2)

BDD frameworks (part 2)

In this series of articles, you can learn how to use automated software testing with Behavior-Driven Development. In part 1, I described the main assumptions of the process. Now it is time for BDD testing tools.

Read more
Mobile Apps

Get your mobile app in 3 easy steps!

1

Spec out

with the help of our
business analyst

2

Develop

design, implement
and test, repeat!

3

Publish

get your app out
to the stores

Contact us

Hire us now!

back to top