iPhone - Auto resizing UIWebView content do not fit the frame

71,297

Solution 1

The answer is: you are already doing this but there are limits.

Look at the following screenshots:

Screeshot 1, scalesPageToFit YES and NO

Both webview have the same width. In the lower one the page fits perfectly.

enter image description here

Screeshot 2, scalesPageToFit both YES but smaller widths set

Both webview try to fit the page but it won't as there is a size limit.

enter image description here

Solution 2

Try this.That's working for me.

NSString *strTemplateHTML = [NSString stringWithFormat:@"<html><head><style>img{max-width:100%%;height:auto !important;width:auto !important;};</style></head><body style='margin:0; padding:0;'>%@</body></html>", @"insert your html content here"];

[webView loadHTMLString:strTemplateHTML baseURL:nil];

Solution 3

For those, who faced same problem, you can turn off the UIWebView native scrolling by

self.webView.scrollView.scrollEnabled = NO;

and add a separate scrollView which will handle scrolling and zooming instead of webView's native scroll. Next implement

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
   CGRect frame = _webView.frame;
   CGSize fittingSize = [_webView sizeThatFits:_webView.scrollView.contentSize];
   frame.size = fittingSize;
   _webView.frame = frame;
   self.scrollView.contentSize = self.webView.scrollView.contentSize;
}

to set proper webView frame. Hope this helps someone. Good coding!

Solution 4

Use sizethatfits() in the webview which would resolve your issue.

Share:
71,297
Oliver
Author by

Oliver

Updated on August 13, 2021

Comments

  • Oliver
    Oliver almost 3 years

    I'm generating an UIWebView into my viewDidLoad method, with a tiny size (let's say something like 50x70). And then I put it into a super UIView.

    I'd like to make its content fit the webView frame. To do this, I wrote :

            oneView = [[UIWebView alloc] initWithFrame:CGRectMake(x, y, W, H)];
            oneView.backgroundColor = [UIColor whiteColor];
            oneView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            oneView.scalesPageToFit = YES;
            oneView.autoresizesSubviews = YES;
    
            [self.view addSubview:oneView];
            [oneView loadRequest:/*some request*/];
    

    But doing this, the web page is not resized to the frame of the UIWebView. It seems to be scaled to something else, smaller than the superview's frame, and wider than the webview's one.

    enter image description here

    If I set the webview frame size to the whole superview's size, it's ok.
    How may I force the web content (real www content) to fit the frame of the "reduced" UIWebView ?