Tuesday, June 4, 2013

UIScrollView scrollsToTop example in Objective C (iOS).

UIScrollView scrollsToTop

A Boolean value that controls whether the scroll-to-top gesture is effective

@property(nonatomic) BOOL scrollsToTop

Discussion of [UIScrollView scrollsToTop]
The scroll-to-top gesture is a tap on the status bar; when this property is YES, the scroll view jumps to the top of the content when this gesture occurs. The default value of this property is YES.

This gesture works on a single visible scroll view; if there are multiple scroll views (for example, a date picker) with this property set, or if the delegate returns NO in scrollViewShouldScrollToTop:, UIScrollView ignores the request. After the scroll view scrolls to the top of the content view, it sends the delegate a scrollViewDidScrollToTop: message.

UIScrollView scrollsToTop example.

You cannot have more than one UIScrollView (or classes deriving from or using UIScrollView - i.e. UITableView) on the same UIView with the property scrollsToTop set to YES. Pick the one you want to have the feature and make sure all others are no

For example, do this:

scrollView.scrollsToTop = NO;
tableView.scrollsToTop = YES; // or not set
Implement the UIScrollView delegate method scrollViewShouldScrollToTop: and return YES if the calling UIScrollView is the UITableView.

Example of [UIScrollView scrollsToTop].
-(void)inspectViewAndSubViews:(UIView*) v level:(int)level {

NSMutableString* str = [NSMutableString string];

for (int i = 0; i < level; i++) {
    [str appendString:@"   "];

[str appendFormat:@"%@", [v class]];

if ([v isKindOfClass:[UITableView class]]) {
    [str appendString:@" : UITableView "];

if ([v isKindOfClass:[UIScrollView class]]) {
    [str appendString:@" : UIScrollView "];

    UIScrollView* scrollView = (UIScrollView*)v;
    if (scrollView.scrollsToTop) {
        [str appendString:@" >>>scrollsToTop<<<<"];

NSLog(@"%@", str);

for (UIView* sv in [v subviews]) {
    [self inspectViewAndSubViews:sv level:level+1];

UIScrollView scrollsToTop example.
- (void) ensureScrollsToTop: (UIView*) ensureView {
    ((UIScrollView *)[[webView subviews] objectAtIndex:0]).scrollsToTop = NO;

- (void)webViewDidFinishLoad:(UIWebView *) wv {   
    [self ensureScrollsToTop: wv];

End of UIScrollView scrollsToTop example article.