无法正确获取 WKWebView 内容高度

Can't get WKWebView content height correctly

我正在尝试获取 WKWebView 中呈现的文本的高度,以便稍后可以调整视图的大小以适合它。我正在使用下面的代码,它通过 result 执行 return 一个值。但是,如果我缩短(或延长)htmlString,这个值不会改变。有什么建议吗?

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

var webView: WKWebView!

var htmlString: String = "<!DOCTYPE html><html><body><p>Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.</p></body></html>"

override func viewDidLoad() {
    super.viewDidLoad()

    //Instantiate with initial frame
    webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 100), configuration: WKWebViewConfiguration())
    self.view.addSubview(webView)

    webView.loadHTMLString(htmlString, baseURL: nil)

    webView.evaluateJavaScript(("document.body.scrollHeight"), completionHandler: { result, error in
        print(result)
    })
}

}

下面的方法应该可以解决问题

      //to get height

          webView.evaluateJavaScript("document.height") { (result, error) in
            if error == nil {
                print(result)
            }
        }

        //to get width
        webView.evaluateJavaScript("document.width") { (result, error) in
            if error == nil {
                print(result)
            }
        }
  // to get contentheight of wkwebview
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {

   println(webView.scrollView.contentSize.height)

}

您的代码存在的问题是您在加载 HTML 字符串后立即评估 document.body.scrollHeight。要获得正确的高度,您必须等到 HTML 加载,这需要一些时间,特别是如果这是您第一次加载 HTML 字符串。
这就是为什么你必须在这个委托方法中评估 document.body.scrollHeight

 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
      webView.evaluateJavaScript("document.documentElement.scrollHeight") { (height, error) in
        print(height as! CGFloat)
      }
  }

我已经写过这个问题以及如何在 CSS 中使用自定义字体的情况下找到正确的高度 blog post

为了获得 webView 的准确高度,您应该确保 webView 未处于加载状态。 这是我使用它的代码。

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.isLoading == false {
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
      if complete != nil {
        webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
          if error == nil {
            guard let height = height as? CGFloat else { return }
            webView.frame.size.height = height
            self.webViewContainerHeightConstraint.constant = height
            webView.sizeToFit()
            self.view.updateConstraints()
            self.view.updateConstraintsIfNeeded()
          }
        })
      }
    })
  }
}}

我在iPhone 5s 上也有问题,宽度不正确。所以我添加了这段代码,以确保正确的框架。

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
myWebView.frame = webViewContainer.bounds }