Monday, June 3, 2013

UIWebView scrollView example in Objective C (iOS).


UIWebView scrollView

The scroll view associated with the web view. (read-only)

@property(nonatomic, readonly, retain) UIScrollView *scrollView

Discussion of [UIWebView scrollView]
Your application can access the scroll view if it wants to customize the scrolling behavior of the web view.

UIWebView scrollView example.
- (UIScrollView *)getScrollViewFromWebView: (UIWebView*) webView {
    UIScrollView *scrollView = nil;

    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:@"5.0" options:NSNumericSearch] != NSOrderedAscending) {
        return webView.scrollView;
    }
    else {
        for (UIView *subview in [webView subviews]) {
            if ([subview isKindOfClass:[UIScrollView class]]) {
                scrollView = (UIScrollView *)subview;
            }
        }

        if (scrollView == nil) {
            NSLog(@"Couldn’t get default scrollview!");
        }
    }
    return scrollView;
}

Example of [UIWebView scrollView].
The issue isn't the setScrollEnabled: call. It's actually that the scrollView of the UIWebView wasn't exposed until iOS 5 (which is why it fails on anything else). See the UIWebView documentation for further information.

In previous versions of iOS, you had to resort to iterating through the subviews of your UIWebView to find a UIScrollView.
UIScrollView* scrollView = nil;
for (UIView* subview in [webView subviews]) {
   if ([subview isKindOfClass:[UIScrollView class]]) { 
      scrollView = (UIScrollView*)subview;
      scrollView.delegate = ;
      break;
   }
}

UIWebView scrollView example.
static int kObservingContentSizeChangesContext;

- (void)startObservingContentSizeChangesInWebView:(UIWebView *)webView {
    [webView.scrollView addObserver:self forKeyPath:@"contentSize" options:0 context:&kObservingContentSizeChangesContext];
}

- (void)stopObservingContentSizeChangesInWebView:(UIWebView *)webView {
    [webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:&kObservingContentSizeChangesContext];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == &kObservingContentSizeChangesContext) {
        UIScrollView *scrollView = object;
        NSLog(@"%@ contentSize changed to %@", scrollView, NSStringFromCGSize(scrollView.contentSize));
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

End of UIWebView scrollView example article.