3

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
j_mcnally
  • 6,928
  • 2
  • 31
  • 46

1 Answers1

12

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.

j_mcnally
  • 6,928
  • 2
  • 31
  • 46
  • 1
    I'm was going crazy about an UIWebView which had a wrong width after a rotation to portrait, this does the trick ! Thanks a lot – Gonzo Oin Aug 13 '13 at 08:46
  • Very old issue, that seems to be fixed in iOS 9, but for iOS 8 and before, setting `document.querySelector` manually is the one that did the trick for me. Thank you! – P.L. Nov 17 '15 at 03:13