IOS UIWebView inside UIScrollView

I want to have a UIWebView inside a UIScrollView . UIWebView sometimes goes beyond the iPhone screen, so I need a way to scroll the view so that I can see all the content (but I don't want to use the built-in UIWebView scroll). So I'm going to put all the content in a UIScrollView, and then make the height of the UIScrollView equal to the height of the UIWebView and other views that are in it.

Here is an image that will help describe my problem:

Interface Builder Image

+17
ios objective-c uiscrollview uiwebview
Jun 22 '11 at 13:13
source share
1 answer

I did the same. Here is how I did it:

  • Add UIWebView as a subtask of UIScrollView (obviously -)
  • Disable native scrolling of the UIWebView (you can do this by iterating through the subviews of the UIWebView until you find its UIScrollView and set scrollEnabled = NO for it.
  • Set the content size of your UIScrollView and the UIWebView frame to the size of the HTML content of the UIWebViews.

The last point is a bit complicated, because you cannot be sure that the HTML is fully displayed when webViewDidFinishLoad: is called in UIWebViewDelegate.

Here's a reliable way to get the size of the HTML content:

1. Add a javascript function to the HTML, which is called when the HTML document is ready:

 window.onload = function() { window.location.href = "ready://" + document.body.offsetHeight; } 

These functions send a request with the height of the content in the URL.

2. In the UIWebViewDelegate, you intercept this request:

 - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { NSURL *url = [request URL]; if (navigationType == UIWebViewNavigationTypeOther) { if ([[url scheme] isEqualToString:@"ready"]) { float contentHeight = [[url host] floatValue]; yourScrollView.contentSize = CGSizeMake(yourScrollView.frame.size.width, contentHeight + yourWebView.frame.origin.y); CGRect fr = yourWebView.frame; fr.size = CGSizeMake(yourWebView.frame.size.width, contentHeight); yourWebView.frame = fr; return NO; } return YES; } 

Hope that helps

UPDATE

Here is the version of Swift 2:

 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard navigationType == .Other else { return true } if let url = request.URL, let host = url.host { guard url.scheme == "ready" else { return true } if let contentHeight = Float(host) { yourScrollView.contentSize = CGSizeMake(yourScrollView.bounds.size.width, CGFloat(contentHeight)) var fr = webView.frame fr.size = CGSizeMake(fr.size.width, CGFloat(contentHeight)) webView.frame = fr } return false } return true } 
+37
Jun 24 2018-11-11T00:
source share



All Articles