为 TableView 启用 3D Touch 预览

Enabling 3D Touch preview for TableView

我有 TableViewController 转至 UIViewControllerWKWebView 所在的位置。每个 TableView 单元格都指向特定的本地 html 文件,然后加载到 WebView 中。

I can simply check the Peek & Pop - Preview & Commit Segues in Attributes Inspector for that segue, but the preview will show always the same html file, rather than different one for each table cell selected.

实施 3D Touch 的正确方法是什么,或者如何以某种方式准备 html 内容以在第一个 TableViewController 中进行预览?


.xcodeproj 在我的 github 上。更多信息点播。

感谢帮助!

好的,我看到了你的代码,但你没有实现 3D 触摸,首先你需要检查 3DTouch 是否在你的 viewDidLoad() 方法中可用:

if( UIApplication.shared.keyWindow?.traitCollection.forceTouchCapability == .available{
registerForPreviewing(with: self, sourceView: view)
}

然后,实现Preview UIViewControllerPreviewingDelegate的delegate,你说的是用3dtouch弹出一个viewcontroller,在delegate

中实现这个功能
extension:YourViewController:UIViewControllerPreviewingDelegate{

   func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
       //Here's where you commit (pop)
       //You are trying to show into tableview, the next code makes this
       //For TableView
      guard let indexPath = tableView?.indexPathForItem(at:location) else { 
      return nil }
      guard  let cell2 = tableview.cellForRow(at: indexPath) else { return nil }
      guard let popVC = storyboard?.instantiateViewController(withIdentifier: "popVC") as? YourClassViewControllerToShow else { return nil }
     let html = htmls[indexPath.row]
     popVC.html = html
     show(popVC, sender: self)

   } 
}

然后我将代码从 Detail.swift viewDidLoads() 切换为 viewWillAppear()

content.uiDelegate = self
  content.navigationDelegate = self
  let url = Bundle.main.url(forResource: result?.id, withExtension: "html", subdirectory: "Library")!
  let request = URLRequest(url: url)
  content.loadFileURL(url, allowingReadAccessTo: url)
  content.load(request)

最后,您可以确保 webview 在出现时始终刷新。

查看时没有选定的单元格,因此您不能只向table询问选定的单元格。相反,您必须处理 sender 参数,即 UITableViewCell:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transporter" {
        guard
            let cell = sender as? UITableViewCell,
            let path = table.indexPath(for: cell)
        else {
            return
        }

        let selected = filtering() ? filter[path.section].rows[path.row] : list[path.section].rows[path.row]
        let controller = (segue.destination as! Detail)
        controller.result = selected
    }
}