marceloquinta marceloquinta - 1 year ago 405
Objective-C Question

UIWebView with dynamic height inside a UIScrollView in Objective-C

I am trying to make a UIWebView with "dynamic screen height". This webview is inside a UIScrollView, below other components. See the layout (it uses autolayout):

enter image description here

My idea is to provide just one scroll (from UIScrollView - its working) and make the WebView viewport grow depending the content size. And its not working.

What I did to try to do this:

  1. UIWebView property "scale page to fit " is on;

  2. UIWebView is unpaginated;

  3. UIWebView does not allow user interaction.

In my UIViewController:

- (void) viewDidAppear:(BOOL)animated {
NSString *urlString = @"MY URL GOES HERE";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[_webViewDescription loadRequest:urlRequest];
_webViewDescription.delegate = self;
_webViewDescription.scrollView.scrollEnabled = NO;
_webViewDescription.scrollView.bounces = NO;

My UIWebViewDelegate:

- (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);

_myScrollView.contentSize = webView.bounds.size;

When I run the code, it prints the correct UIScrollView size and UIWebView size. The UIScrollView height got bigger, but the UIWebView maintains the same height from the first loading.

I am testing in a real device.

Answer Source

add a height constraint to your webView and make a IBOutlet of that like

@property(strong, nonatomic) IBOutlet NSLayoutConstraint *webViewHeightConstraint;

load your webview and in web view delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView

get webview content height and set webViewHeightConstraint.constant like below:-

    - (void)webViewDidFinishLoad:(UIWebView *)webView

    NSString *str = [webView stringByEvaluatingJavaScriptFromString:@"(document.height !== undefined) ? document.height : document.body.offsetHeight;"];
    CGFloat height = str.floatValue;
    webViewHeightConstraint.constant = height;


hope it may help you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download