How to detect scrollView scrolling direction?

2019-04-02 09:58发布

问题:

I have a UIScrollView inside that I have a UITableView The scroll view should scrol horizontally. And I have implemented - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView to do some tasks when the scroll view end its horizontal scrolling. But My problem is, this delegate is firing even when the UITableView vertical scrolling stopped too. So how can I detect just the scrollview horizontal scrolling within this delegate?

Please help me, Thanks

回答1:

Check these delegate methods

CGPoint _lastContentOffset;

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  _lastContentOffset = scrollView.contentOffset;
}

  - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    if (_lastContentOffset.x < (int)scrollView.contentOffset.x) {
      NSLog(@"Scrolled Right");
    }
    else if (_lastContentOffset.x > (int)scrollView.contentOffset.x) {
      NSLog(@"Scrolled Left");
    }

    else if (_lastContentOffset.y < scrollView.contentOffset.y) {
      NSLog(@"Scrolled Down");
    }

    else if (_lastContentOffset.y > scrollView.contentOffset.y) {
      NSLog(@"Scrolled Up");
    }
}