Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if scrollView is about to be scrolled up or down

I would like to find out if a scrollView is scrolled up or down. Ideally, I'd like to have only one call if the scrollView is scrolled up or down. I tried this but it will obviously not tell me anything about the direction:

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"%.2f", scrollView.contentOffset.y);
}

contentOffset will always be 0 - it doesn't matter whether I scrolled up or down. Now I could simply check in -(void)scrollViewDidScroll: if the offset is positive or negative, but this is called constantly. scrollViewWillBeginDragging has the advantage of being called only once and this is what I need. Is there something like scrollViewDidBeginDragging? I didn't find anything in the docs. Any smart workaround?

like image 351
n.evermind Avatar asked Dec 04 '22 04:12

n.evermind


1 Answers

Store the initial content offset in scrollViewWillBeginDragging:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.initialContentOffset = scrollView.contentOffset.y;
    self.previousContentDelta = 0.f;
}

And check it on each scrollViewDidScroll:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat prevDelta = self.previousContentDelta;
    CGFloat delta = scrollView.contentOffset.y - self.initialContentOffset;
    if (delta > 0.f && prevDelta <= 0.f) {
        // started scrolling positively
    } else if (delta < 0.f && prevDelta >= 0.f) {
        // started scrolling negatively
    }
    self.previousContentDelta = delta;
}
like image 102
John Calsbeek Avatar answered Apr 13 '23 00:04

John Calsbeek