Search code examples
iosswiftuitableviewforce-touch

How to implement Peek & Pop Feature of specific row of a table manually via code?


Goal

I'm trying to add the peek and pop feature to my table row


enter image description here


Solution

  • You are not getting the cell from the tableview. So the steps are as follows:

    1. Get the indexPath using the location point from UIViewControllerPreviewingDelegate method.
    2. Use the indexPath to get cell from the tableView.
    3. After getting the cell convert the cell frame to tableview frame.
    4. Give the frame as sourceRect to previewingContext.

    Code Below:

    In viewDidLoad

    if self.traitCollection.forceTouchCapability == .available {
        registerForPreviewing(with: self, sourceView: tableView)
    }
    

    In Extension:

    extension ProfileViewController: UIViewControllerPreviewingDelegate {
    
        func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
            if let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) {
                previewingContext.sourceRect = tableView.convert(cell.frame, to: self.tableView)
                guard let detailViewController = storyboard?.instantiateViewController(withIdentifier: "profileDetail") as? ProfileDetailViewController else {
                    return nil
                }
                return detailViewController
            }
            return nil
        }
    
        func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
            self.navigationController?.pushViewController(viewControllerToCommit, animated: true)
        }
    }