UIWebView:获取 Webview 内容大小?

UIWebView : Get Webview Content size?

我已经在网络视图中加载了 HTML。我想动态更新网页视图中加载的文本的字体大小(增加或减少) 与 Apple News Article 应用程序相同。但根据我的设计,我需要停止 web 视图滚动并需要根据文本更新它的高度。所以我需要获取文章的内容大小,但我没有得到正确的。有人可以帮忙吗?

将以下代码行添加到您的 webViewDidFinishLoad

        webView.layoutSubviews()
        webView.frame.size.height = 1
        webView.frame.size = webView.sizeThatFits(.zero)
        print("WebView Height : \(webView.scrollView.contentSize.height)")
        webViewHgtConst.constant = webView.scrollView.contentSize.height
        webView.scalesPageToFit = true
        webView.scrollView.isScrollEnabled = false
        webView.scrollView.maximumZoomScale = 1.0
        webView.scrollView.minimumZoomScale = 1.0

并且不要忘记添加 UIWebViewDelegate 并将 YOUR_WEBVIEW.delegate = self 添加到您的 viewDidLoad

希望对您有所帮助

首先停止滚动:

         webView.scrollView.isScrollEnabled = false
         webView.scrollView.showsVerticalScrollIndicator = false
         webView.scrollView.showsHorizontalScrollIndicator = false
         webView.scrollView.bounces = false
         webView.loadHTMLString(dataHtmlString, baseURL: nil)

对webView的outlet做高度约束,通过计算高度给定值:

     webviewHeightConst.constant  = (dataHtmlString.htmlAttributedString()?.height(withConstrainedWidth: yourwidthcont))!

此扩展计算高度

extension String {

func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }

    var found = false

    html.beginEditing()
    html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
        if (value != nil) {
                            let oldFont = value as! UIFont
                           let newFont = oldFont.withSize(16)
            html.addAttribute(NSFontAttributeName, value: newFont, range: range)
            found = true
        }
    }

    if !found{
        // No font was found - do something else?
    }
    html.endEditing()

    return html
}
}

当时更改字体时,将 Webview 高度更改为 1,然后为 Webview

获得正确的 offsetHeight
webView1.frame.size.height = 1
let size : String = self.webView1.stringByEvaluatingJavaScript(from: "document.documentElement.offsetHeight")!