Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView not loading responsive web page correctly

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?

like image 240
Darren Avatar asked May 30 '14 16:05

Darren


2 Answers

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]];
}
like image 122
Darren Avatar answered Oct 04 '22 02:10

Darren


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

webView.scalesPageToFit = TRUE;

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

like image 35
Ravi Sharma Avatar answered Oct 04 '22 02:10

Ravi Sharma