Dynamic height of UIWebView with auto layout

13,225

Solution 1

You have to add some code in the delegate method of UIWebView named webViewDidFinishLoad. Here is what you can do:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
      CGRect frame = webView.frame;
      frame.size.height = 1;
      webView.frame = frame;
      CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
      frame.size = fittingSize;
      webView.frame = frame;

      NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);

      yourScrollView.contentSize = webView.bounds.size; 
}

The same thing can also be achieved using javascript to find the right height which is as follow:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGRect oldBounds = [[self webView] bounds];
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];
    NSLog(@"NEW HEIGHT %f", height);
    [webView setBounds:CGRectMake(oldBounds.origin.x, oldBounds.origin.y, oldBounds.size.width, height)];
    yourScrollView.contentSize = webView.bounds.size;
}

Hope it helps!

Solution 2

I actually had the same problem recently and ended up figuring it out and putting together a sample project on github.

Share:
13,225
ruhu
Author by

ruhu

Updated on June 06, 2022

Comments

  • ruhu
    ruhu almost 2 years

    I have a problem with setting the height of an UIWebView dynamically. The webview loads a product description which contains html. I want the UIWebView to change its height based on the contents of the description. The parent scrollview should also change its height, but then based on the height of the UIWebView.

    Can anyone explain to me how I can achieve the desired behavior of my views?

    This is my view hierarchy:

    enter image description here

  • ruhu
    ruhu over 10 years
    I have a constant height constraint on the webview, how and where can I change the height? Is is in the webviewdidfinishload method?
  • tng
    tng about 9 years
    For the record, I have searched high and low for this, and your project was the best help in getting all the auto layout constraints sorted out.
  • Julian F. Weinert
    Julian F. Weinert almost 8 years
    But extremely inaccurate. I get content cut off
  • Rajesh73
    Rajesh73 over 6 years
    To get accurate result, Use observer for contentSize to webView.scrollView