UIWebview won't zoom even after setting scales

2019-02-02 17:18发布

问题:

I have a UIWebview that is loaded as a subview when a user selects a tab on a UISegmentedControl. For some reason, I can not get it to allow pinch/zooming. I set the following code in the viewDidLoad: method, so it should work.

self.myWebView = [[[UIWebView alloc] initWithFrame:self.view.frame] autorelease];
self.myWebView.backgroundColor = [UIColor whiteColor];
self.myWebView.scalesPageToFit = YES;
self.myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.myWebView.delegate = self;
[self.view addSubview: myWebView];

I tried loading a UIWebView from a NIB and creating it programmatically with no avail. Is there something I'm missing? What could be causing the webview to ignore pinching and zooming?

Thanks!

回答1:

I see you are setting the autoresizingMask. Does that mean you have created the UIWebView with an initial size of CGRectZero ? Can you interact with the document at all? I mean, does scrolling/tapping work?



回答2:

  [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.zoom = 5.0;"];

seem to be the suitable solution



回答3:

I solved this with setting a view port:

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.5; user-scalable=1"/>

Good luck



回答4:

In my experience, you need to set scalesPageToFit before the UIWebView loads. This means setting before viewDidLoad etc. What I do is set it in "shouldStartLoadWithRequest"

- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //make sure that the page scales when it is loaded :-)
    theWebView.scalesPageToFit = YES;
    return YES;
}

My interpretation of the documentation is that the scalesPageToFit property dictates how the page WILL be loaded. It does not alter things after the fact.

Hope this helps.



回答5:

FYI:

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.5; user-scalable=1"/>

works but

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.5; user-scalable=YES"/>

does not on the iPhone. The documentation says to use yes/no. I guess case matters in this case. In obj-c the values are YES/NO and 1/0



回答6:

You have to enable multi-touch. Pinch involves more than one finger on the screen:

[myWebView setMultipleTouchEnabled:YES]



回答7:

This is what Apple suggests in the webview class reference.

Important: You should not embed UIWebView or UITableView objects in UIScrollView objects. If you do so, unexpected behavior can result because touch events for the two objects can be mixed up and wrongly handled.