1

One of the standard gestures in iOS is, by tapping the status bar (the bar at the top of the screen with your signal level, battery strength, etc.), that will automatically scroll any content (e.g. in a table view, scroll view, etc.) to the top.

I'm writing an app that interfaces with a chat server. As new chat messages are received, they get added to the bottom of a UITextView. The user can scroll back to look at previous chat history of course.

Is it possible to override the "tap the status bar" shortcut so that instead of scrolling to the top, it instead can call one of my own methods? (I have a method in my view controller that automatically scrolls the chat window to the bottom).

Donald Burr
  • 2,281
  • 2
  • 23
  • 31
  • Check this: http://stackoverflow.com/questions/3753097/how-to-detect-touches-in-status-bar/16787113#16787113 – Aron Balog May 31 '13 at 12:48

2 Answers2

2

This is what I come up with. The key is to override scrollViewShouldScrollToTop: method. And to return NO to prevent the default behavior.
One thing to be aware of is that scrollViewShouldScrollToTop: won't be called if the content of the scroll view is already at the top of the scroll view. See the trick in the code below.

@interface ViewController ()
<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width,
                                             self.view.bounds.size.height * 2);

    // if the scrollView contentOffset is at the top
    // (0, 0) it won't call scrollViewShouldScrollToTop
    self.scrollView.contentOffset = CGPointMake(0, 1);
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    // call your custom method and return YES
    [self scrollToBottom:scrollView];
    return NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // be sure that when you are at the top
    // the contentOffset.y = 1
    if (scrollView.contentOffset.y == 0)
    {
        scrollView.contentOffset = CGPointMake(0, 1);
    }
}

- (void)scrollToBottom:(UIScrollView *)scrollView
{
    // do whatever you want in your custom method.
    // here it scrolls to the bottom
    CGRect visibleRect = CGRectMake(0, scrollView.contentSize.height - 5, 1, 1);
    [scrollView scrollRectToVisible:visibleRect animated:YES];
}

@end
grandouassou
  • 2,500
  • 3
  • 25
  • 60
0

Try this:

- (void)myMethod {

    [myScrollableObject setScrollsToTop:NO];
}

Any object inheriting UIScrollView should have this property.

Reference

Simon Germain
  • 6,834
  • 1
  • 27
  • 42