Ios – UIWebView not loading responsive web page correctly

iosios7uiwebview

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?

Best Answer

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]];
}
Related Topic