I am trying to get the height of text rendered within a WKWebView so that I can later resize the view to fit it. I am using the code below, which does return a value via result
. However if I shorten (or lengthen) htmlString
, this value doesn't change. 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)
})
}
}