UIWebView scaling page so that there is no need fo

2020-08-05 10:19发布

问题:

Is there a way to scale a web page in a UIWebView that maintains the aspect ratio but alleviates the need to scroll horizontally to read an article, for example. Vertical scrolling is fine, I just don't want the user to have to constantly be scrolling back and forth horizontally to read each line of the article. Thanks!

Edit: the code I'm using to create the view

    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [[self view] frame].size.height)];
    [_webView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
    [_webView setDelegate:self];
    [_webView setScalesPageToFit:YES];
    [_webView loadRequest:[NSURLRequest requestWithURL:[headline link]]];

The link is always formatted for mobile already.

回答1:

I think that defining the viewport for your UIWebView could help:

<meta name="viewport" content="width=device-width"/>

this is to use the full width of the device; if your UIWebView is smaller, that you can specify its width in points.

In case you need to add the meta tag to the HTML of your page after loading it, you can use this code:

- (void) webViewDidFinishLoad:(UIWebView *)webView {

  NSString* js = 
  @"var meta = document.createElement('meta'); "
   "meta.setAttribute( 'name', 'viewport' ); "
   "meta.setAttribute( 'content', 'width = device-width' ); "
   "document.getElementsByTagName('head')[0].appendChild(meta)";

  [webView stringByEvaluatingJavaScriptFromString: js];        
}

Also check this S.O. thread for another technique for the same.