UIWebView — load external website, programmatically set initial zoom scale, and allow user to zoom afterwards

You can add or modify a <meta name="viewport" tag to achieve this. Apple documentation on the meta/viewport tag here:

https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html

Here’s an example of adding the tag once the document is loaded:

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    NSString* js = 
    @"var meta = document.createElement('meta'); " \
     "meta.setAttribute( 'name', 'viewport' ); " \
     "meta.setAttribute( 'content', 'width = device-width, initial-scale = 5.0, user-scalable = yes' ); " \
     "document.getElementsByTagName('head')[0].appendChild(meta)";

    [webView stringByEvaluatingJavaScriptFromString: js];        
}

If the web page you’re loading provides an existing meta tag you may need to modify it rather than attempting to add a new meta element to the DOM. This SO question discusses the technique:

Can I change the viewport meta tag in mobile safari on the fly?

In my test app I set the UIWebView scalesPageToFit to YES.

Leave a Comment