uiwebview height calculation in swift

2019-07-31 07:22发布

i have a scrollview and want to add multiple webviews dynamically into it. need to get height of webview. i have used below code. but it does't work always.some times showing wrong height. func webViewDidFinishLoad(aWebView: UIWebView) {

    let screenSize      = UIScreen.mainScreen().bounds
    let screenWidth     = screenSize.width
    var frame           = aWebView.frame
    frame.size.height   = 1
    frame.size.width    = screenSize.width
    aWebView.frame      = frame
    let fittingSize     = aWebView.sizeThatFits(CGSizeZero)
    frame.size          = fittingSize
    aWebView.frame      = frame

}

1条回答
疯言疯语
2楼-- · 2019-07-31 08:21

This is a really good question, fitting web views to their content has interesting applications, such as showing an info windows on a map using a web view that fits to its content.

Here is a solution using WKWebView that begins by creating a 1-by-1px size web view, loading its content, and querying the web view to find its content size before updating the web view frame size accordingly. Slightly hacky but seems to be the only way.

import WebKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
        view.addSubview(webView)
        webView.navigationDelegate = self
        let htmlFile = Bundle.main.path(forResource: "index", ofType: "html")
        let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        webView.loadHTMLString(html, baseURL: nil)
    }
}

extension ViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        var frame = webView.frame
        webView.evaluateJavaScript("document.documentElement.offsetWidth", completionHandler: { ret, _ in
            guard let width = ret as? CGFloat else { return }
            print("setting width: ", width)
            frame.size.width = width
            webView.frame = frame

            webView.evaluateJavaScript("document.documentElement.offsetHeight", completionHandler: { ret, _ in
                guard let height = ret as? CGFloat else { return }
                print("setting height: ", height)
                frame.size.height = height
                webView.frame = frame
            })
        })
    }
}

My sample HTML file (index.html):

<html>
    <head>
        <meta name="viewport" content="width=150, initial-scale=1.0">
    <style>
        html, body { margin: 0; padding: 0 };

    </style>
    </head>
    <body>
        <div style="height:280px;width:150px;background-color:cyan;"></div>
    </body>
</html>

Note: You should try to use the WKWebView instead of the UIWebView if possible. A UIWebView solution may be possible, but I don't think it's worthy of the time and effort when the WKWebView should fit your needs better.

查看更多
登录 后发表回答