iosswiftuicontextmenuconfigurationxcode11.1

Click preview to show destination VC


I've tried to implement a new UIContextMenuConfiguration to my tableView based app. I've also added a new delegate methods as shown below. It's works well, but I would like add a feature something like native iOS 13 apps. Click Preview to show destination!

My question is: Is it possible to implement such a feature? I am using Xcode 11.1 GM and Swift 5.1

override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
    let provider = UIContextMenuConfiguration.init(identifier: indexPath as NSCopying, previewProvider: { () -> UIViewController? in
        let vc = ViewController.init()
        return vc
    }) { (elements) -> UIMenu? in
        let addToList = UIAction.init(title: "Add to list") { (action) in
            self.performSegue(withIdentifier: "id", sender: self)
        }
        addToList.image = UIImage.init(systemName: "plus")
        return UIMenu.init(title: "", image: nil, identifier: nil, options: .destructive, children: [addToList])
    }
    return provider
}

override func tableView(_ tableView: UITableView, willCommitMenuWithAnimator animator: UIContextMenuInteractionCommitAnimating) {
    if let vc = animator.previewViewController {
        self.show(vc, sender: self)
    }
}

Solution

  • I've found my problem, this is my fault. I've used a wrong method, so I just replaced with the right one. I've replaced the willCommitMenuWithAnimator method to willPerformPreviewActionForMenuWith, and work well:

    override func tableView(_ tableView: UITableView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
        animator.preferredCommitStyle = .pop
        animator.addCompletion {
            guard let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(identifier: "ViewController") as? ViewController else { return }
            // 1. Present option
            self.present(vc, animated: true, completion: nil)
    
            // 2. Push option
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }