请稍侯

动态获得wkwebview的高度

18 January 2024

动态获得WKWebView的content高度并更新

//计算并更新 webViewCell 高度
private var lastContentHeight: CGFloat = Const.kDefaultWebViewHeight
private func updateContentHeight() {
    webView.evaluateJavaScript("document.readyState", completionHandler: { [weak self] (complete, error) in
        guard let self = self, complete != nil else {
            self?.contentView.snp.updateConstraints { make in
                make.height.equalTo(Const.kDefaultWebViewHeight)
            }
            return
        }
        self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { [weak self] (height, error) in
            guard let self = self, var height = height as? CGFloat else { return }
            let zoomScale = self.webView.scrollView.zoomScale
            debugPrint("===== webview scrollHeight:\(height) zoomScale:\(zoomScale)")
            height = height * zoomScale
            if height != self.lastContentHeight {
                self.lastContentHeight = height
                self.contentView.snp.updateConstraints { make in
                    make.height.equalTo(height)
                }
                //self.webView.layoutIfNeeded()
                self.updateLayoutBlock?()
            }
        })
    })
}

//updateLayoutBlock 回调更新 tableView
let updateLayoutBlock = { [weak tableView] in
    UIView.performWithoutAnimation {
        do {
            tableView?.beginUpdates()
            tableView?.endUpdates()
        } catch let error {
            debugPrint("Caught an unknown exception: \(error).")
        }
    }
}

webViewCell.updateLayoutBlock = updateLayoutBlock