我试图通过引用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
答案 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
})
}
})
}