Search code examples
swiftuitableview3dtouch

Using 3D Touch with storyboard's peek and pop


I found very easy way to use 3D Touch — check "Peek & Pop" in storyboard. But I'm struggling with one problem.

I have UITableView, when user touches cell all is working ok with my code:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDetail" {
        print(tableView.indexPathForSelectedRow)
    }
}

So I'm filling data in my Detailed controller based on selected row. But when I'm pressing with Peek or Pop method tableView.indexPathForSelectedRow always returning nil (hm.. I haven't selected row, I'm just previewing so indexPath is nil I guess). How can I get that "peeked" cell indexPath to pass it to segue?

Or storyboard's Peek & Pop not working in this simple way and I need to fully implement peek & pop in my code?


Solution

  • It is possible to fully implement it using the storyboard and prepareForSegue. You can do this by making use of the sender object.

    By assuming that you have created your segue directly from the table cell in the storyboard to the next view controller, then the sender object will be of the type UITableViewCell. If you trigger the segue programmatically, then just remember to set the sender object in the method call.

    You can use this cell to get a hold of the NSIndexPath from the tableView, something similar to the following (ignore all the force unwrapping, this is just for demonstration purposes):

    override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
        let cell = sender as! UITableViewCell
        let indexPath = tableView.indexPath(for: cell)!
        if segue.identifier == "mySegue" {
            let destination = segue.destination as! DetailsViewController
            destination.model = self.model[indexPath.row]
        }
    }