Using 3D Touch with storyboard's peek and pop
Asked Answered
T

1

10

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?

Threepiece answered 9/1, 2016 at 13:43 Comment(0)
I
22

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]
    }
}
Irisation answered 8/3, 2016 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.