我正在尝试使用didFinish导航修复collectionview中的WKWebView动态内容大小

时间:2019-05-16 08:58:41

标签: ios swift wkwebview

我试图通过引用WKWebView来增加collectionView内部collectionViewCell的动态内容的大小。一切正常,但有时在展开以下行的Optional值时抛出意外发现的nil:

let cell:CollectionViewCell = collectionView!.cellForItem(at: indexpath) as! CollectionViewCell

这是我的代码:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let indexpath: IndexPath = IndexPath.init(item: pageControl.currentPage, section: 0)
        let cell:CollectionViewCell = collectionView!.cellForItem(at: indexpath) as! CollectionViewCell
         cell.newsWebView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
            if complete != nil {
                cell.newsWebView.evaluateJavaScript("document.body.offsetHeight", completionHandler: { (height, error) in
                    cell.webviewHeightConstraint.constant = height as! CGFloat
                })
            }

        })
    }
  

致命错误:解开可选值时意外发现nil

1 个答案:

答案 0 :(得分:0)

尝试一下。该崩溃可能是由于渲染延迟所致。

let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
       let indexpath: IndexPath = IndexPath.init(item: pageControl.currentPage, section: 0)
        let cell:CollectionViewCell = collectionView!.cellForItem(at: indexpath) as! CollectionViewCell
         cell.newsWebView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
            if complete != nil {
                cell.newsWebView.evaluateJavaScript("document.body.offsetHeight", completionHandler: { (height, error) in
                    cell.webviewHeightConstraint.constant = height as! CGFloat
                })
            }

        })         
}