0

I want to add the dynamic height to UIWebView based on the content of the WebView.

I am loading the HTML file in my webView.

I have also referred to the following link.

UIWebView dynamic content size

But didn't get the result.

Here is my code....

self.mapWebView.delegate = self
let mapHtmlFile = Bundle.main.path(forResource: "map", ofType: "html")
let html = try? String(contentsOfFile: mapHtmlFile!, encoding: String.Encoding.utf8)
self.mapWebView.loadHTMLString(html!, baseURL: nil)

Delegate method

func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.frame.size.height = 1
    webView.frame.size = webView.sizeThatFits(.zero)
    webView.scrollView.isScrollEnabled=false;
    self.cnDirectionWebViewHeight.constant = webView.scrollView.contentSize.height
    webView.scalesPageToFit = true

   // tried following code. Doesn't work
   //webView.frame.size.height = 1
   //webView.frame.size = webView.sizeThatFits(CGSize.zero)
}

Can anyone help me to get out this trouble?

Thanks in advance....

Kuldeep
  • 4,466
  • 8
  • 32
  • 59
VishalPethani
  • 854
  • 1
  • 9
  • 17

1 Answers1

0

A quick solution would be to achieve it using frames and not constraints. Replace your current implementation of func webViewDidFinishLoad(_ webView: UIWebView) {} with this:

func webViewDidFinishLoad(_ webView: UIWebView) {
    webView.scrollView.isScrollEnabled=false;
    let height = webView.scrollView.contentSize.height
    webView.scalesPageToFit = false
    webView.frame.size.height = height
}

Using Constraints :

    func webViewDidFinishLoad(_ webView: UIWebView) {
       webView.scrollView.isScrollEnabled=false
       webView.scalesPageToFit = false
       self.cnDirectionWebViewHeight.constant = 
       webView.scrollView.contentSize.height
       webView.layoutIfNeeded()
    }
Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45