Search code examples
iosios5

On iOS 5, UIWebView is reporting wrong content size for scroll view


I have tried a bunch of "solutions" but for right now I am trying to figure out the content size of the scrollview of a UIWebView. It is currently always returning 1024 which is the width of the device. This doesn't make sense since I am querying the height and the view is in portrait orientation.

The following code reports the height as 1024.00000

-(void)webViewDidFinishLoad:(UIWebView *)webView {

  float sourcesWebViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] floatValue];

  NSLog(@"%f", sourcesWebViewHeight);

}

But I only have a few lines of text.


Solution

  • I'll break down what finally solved this for me.

    I had to wrap my content in this.

    <html><head><meta name=\"viewport\" content=\"initial-scale=1, user-scalable=no, width=device-width\" /></head><body>%@</body></html>
    

    implement the following view did load.

    -(void)webViewDidFinishLoad:(UIWebView *)webView {
    
      [self layoutSubviews];
    
      webView.scrollView.scrollEnabled = NO;    // Property available in iOS 5.0 and later
      CGRect frame = webView.frame;
    
    
      frame.size.height = 1;        // Set the height to a small one.
    
      webView.frame = frame;       // Set webView's Frame, forcing the Layout of its embedded scrollView with current Frame's constraints (Width set above).
    
      frame.size.height = webView.scrollView.contentSize.height;  // Get the corresponding height from the webView's embedded scrollView.
    
      webView.frame = frame;
    
    
    
    
    
    }
    

    and

    -(void) layoutSubviews {
      [super layoutSubviews];
      [body stringByEvaluatingJavaScriptFromString:
       [NSString stringWithFormat:
        @"document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%d;', false); ",
        (int)body.frame.size.width]];
    }
    

    and finally my webview does all the right things to scale itself to the content.