UIWebView dynamic content size

后端 未结 9 1631
北海茫月
北海茫月 2020-12-01 09:21

I\'ve been looking around and wasnt able to see any swift related ways to do this. I\'m trying to get my UIWebViews height to be dynamic. I have a UIWebView that loads data

9条回答
  •  借酒劲吻你
    2020-12-01 10:06

    I had problem with:

    let height = webView.scrollView.contentSize.height
    

    Sometimes my web view height simply didn't calculacte and stayed on default value. So finally I manage to find better solution that works fine, just replace that line code with:

    let height = webView.stringByEvaluatingJavaScript(from: "document.body.scrollHeight")
    

    This is mine final complete code:

        func webViewDidFinishLoad(_ webView: UIWebView) {
    
        //webview height
        webView.frame.size.height = 1
        webView.frame.size = webView.sizeThatFits(.zero)
        webView.scrollView.isScrollEnabled = false
        let height = webView.stringByEvaluatingJavaScript(from: "document.body.scrollHeight")
        if let height = height {
            if let heightInt = Int(height) {
                let heightFloat = Float(heightInt)
    
                webViewHeightConstraint.constant = CGFloat(heightFloat)
            }
        }
        webView.scalesPageToFit = true
    }
    

提交回复
热议问题