簡體   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