UIWebView not loading responsive web page correctly

12,355

Solution 1

I figured out what was happening. My UIWebView width on the iPad is smaller than the device width. The web page was using the device width to determine the width of the page (this code was in the <head> element):

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

I was able to fix the issue using something I found in another question (https://stackoverflow.com/a/13113820/472344):

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

Solution 2

You can achieve this by setting UIWebView property scalesPageToFit to TRUE.

webView.scalesPageToFit = TRUE;

This help me to use responsive webpage's inside UIWebView.

Solution 3

Another way to do this is to use layout constraints in the storyboard. You can simply drag the webview to the parent view and ask for equal width. It is also better to set the constraint from webview to the top layout to 0 to prevent the status bar from overlapping your webview.

enter image description here

Share:
12,355
Darren
Author by

Darren

Updated on June 04, 2022

Comments

  • Darren
    Darren almost 2 years

    I am trying to load a responsive web page into a UIWebview, using the following code in my UIViewController's viewDidLoad method:

    NSURL *url = [NSURL URLWithString:self.webViewURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    

    Rather than loading the web page the way that it should look based on the UIWebView's frame size, it is setting the UIWebView's UIScrollView contentSize to some seemingly arbitrary size (larger than my web view frame size) and loading the responsive web page as it would look for that size frame.

    If I try loading the url that I'm using in Safari, it rearranges correctly according to the browser window size.

    I have tried setting the scalesPageToFit property to YES, although I don't actually want to scale the page, but have it behave responsively to the web view frame.

    Does anyone have any ideas as to what is happening and how I could fix it?