繁体   English   中英

无法正确获取 WKWebView 内容高度

[英]Can't get WKWebView content height correctly

我正在尝试获取 WKWebView 中呈现的文本的高度,以便以后可以调整视图的大小以适应它。 我正在使用下面的代码,它确实通过result返回一个值。 但是,如果我缩短(或加长) 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)
    })
}

}

您的代码的问题在于您在加载 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 中的自定义字体的情况下找到正确的高度。

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

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

}

为了获得 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 }

暂无
暂无

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

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