简体   繁体   English

无法正确获取 WKWebView 内容高度

[英]Can't get WKWebView content height correctly

I am trying to get the height of text rendered within a WKWebView so that I can later resize the view to fit it.我正在尝试获取 WKWebView 中呈现的文本的高度,以便以后可以调整视图的大小以适应它。 I am using the code below, which does return a value via result .我正在使用下面的代码,它确实通过result返回一个值。 However if I shorten (or lengthen) htmlString , this value doesn't change.但是,如果我缩短(或加长) htmlString ,该值不会改变。 Any suggestions?有什么建议吗?

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)
    })
}

}

The problem with your code is that you evaluate document.body.scrollHeight immediately after loading the HTML string.您的代码的问题在于您在加载 HTML 字符串后立即评估document.body.scrollHeight To get the correct height you have to wait until the HTML loads which takes some time, especially if it's the first time you are loading the HTML string.要获得正确的高度,您必须等待 HTML 加载,这需要一些时间,尤其是在您第一次加载 HTML 字符串时。
That is why you have to evaluate document.body.scrollHeight in this delegate method:这就是为什么您必须在此委托方法中评估document.body.scrollHeight的原因:

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

I've written about this issue and how to find the correct height in situations where you use a custom font in CSS in this blog post .我已经写过关于这个问题以及如何在这篇博文中使用 CSS 中的自定义字体的情况下找到正确的高度。

following method should do a trick以下方法应该可以解决问题

      //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)

}

In order to get the exact height of the webView you should be sure that the webView is not on loading state.为了获得 webView 的确切高度,您应该确保 webView 不在加载状态。 Here is the code that I used it.这是我使用它的代码。

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()
          }
        })
      }
    })
  }
}}

I had also a problem on iPhone 5s, the width was not correct.我在 iPhone 5s 上也有问题,宽度不正确。 So I added this code, to ensure the correct frame.所以我添加了这个代码,以确保正确的框架。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM