有时候我们需要检测当前UIScrollView的滑动方向来做出相应的处理,可以借助UIScrollView的delegate函数来实现, 下面的例子可以检测到UIScrollview当前是向上滑动还是向下滑动:
- int _lastPosition; //A variable define in headfile
- - (void)scrollViewDidScroll:(UIScrollView *)scrollView{
- int currentPostion = scrollView.contentOffset.y;
- if (currentPostion - _lastPosition > 25) {
- _lastPosition = currentPostion;
- NSLog(@"ScrollUp now");
- }
- else if (_lastPosition - currentPostion > 25)
- {
- _lastPosition = currentPostion;
- NSLog(@"ScrollDown now");
- }
- }
25 可以是任意数字,可根据自己的需要来设定。
而UItableView是UIscrollView的子类,自然有UIscroolView的特性。如果判断UItableView的滚动方向,如下
- int _lastPosition; //A variable define in headfile
- - (void)scrollViewDidScroll:(UIScrollView *)scrollView{
- int currentPostion = tableView.contentOffset.y;
- if (currentPostion - _lastPosition > 25) {
- _lastPosition = currentPostion;
- NSLog(@"ScrollUp now");
- }
- else if (_lastPosition - currentPostion > 25)
- {
- _lastPosition = currentPostion;
- NSLog(@"ScrollDown now");
- }
- }