UIWebView does not scale content to fit

前端 未结 11 871
忘了有多久
忘了有多久 2020-11-29 00:21

I have a webview which is the top window in the hierarchy and has been declared as shown below. However, it does not scale pages to fit. Pages are top left aligned, but are

相关标签:
11条回答
  • 2020-11-29 00:57

    As mprivate mentions here you can update the zoom level of the UIWebView.

    - (void)webViewDidFinishLoad:(UIWebView *)theWebView {
      CGSize contentSize = theWebView.scrollView.contentSize;
      CGSize viewSize = theWebView.bounds.size;
    
      float rw = viewSize.width / contentSize.width;
    
      theWebView.scrollView.minimumZoomScale = rw;
      theWebView.scrollView.maximumZoomScale = rw;
      theWebView.scrollView.zoomScale = rw;  
    }
    

    Another way of achieving this would be injecting js code on the webViewDidFinishLoad as RunLoop says.

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
      CGFloat scale = 0.8; // the scale factor that works for you 
      NSString *js = [NSString stringWithFormat:@"document.body.style.zoom = %f;",scale];
      [webView stringByEvaluatingJavaScriptFromString:js];
    }
    
    0 讨论(0)
  • 2020-11-29 00:57

    For Swift 3, using RunLoop's effective answer:

    self.webView.stringByEvaluatingJavaScript(from: "document.body.style.zoom = 1.5;")

    0 讨论(0)
  • 2020-11-29 00:58

    My solution in swift:

    "Scales pages to fit" on webView needs to be checked in interface builder.

    Use UIWebViewDelegate.

    func webViewDidFinishLoad(webView: UIWebView) {
        let zoom = webView.bounds.size.width / webView.scrollView.contentSize.width
        webView.scrollView.setZoomScale(zoom, animated: true)
    }
    
    0 讨论(0)
  • 2020-11-29 01:04

    If you have access to the html you are loading you can chuck the following meta tag in the header :

    <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
    
    0 讨论(0)
  • 2020-11-29 01:09

    Try this in your ViewController's viewDidLoad

    [self.myWebView setFrame:CGRectMake(self.view.frame.origin.x,
                                       self.view.frame.origin.y,
                                       self.view.frame.size.width,
                                       self.view.frame.size.height)];
    
    • I also have the webview set to "scalePageToFit" and viewmode set to "Aspect Fit" in my Storyboard.
    0 讨论(0)
提交回复
热议问题