如何知道UITableView以哪种方式滚动
有什么办法可以知道UITableView
是向上滚动还是向下滚动?
-(void) scrollViewDidScroll:(UIScrollView *)scrollView { CGPoint currentOffset = scrollView.contentOffset; if (currentOffset.y > self.lastContentOffset.y) { // Downward } else { // Upward } self.lastContentOffset = currentOffset; }
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{ if (velocity.y > 0){ NSLog(@"up"); } if (velocity.y < 0){ NSLog(@"down"); } }
我们可以这样吗?
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { if ([scrollView.panGestureRecognizer translationInView:scrollView].y > 0) { // down } else { // up } }
UITableView
是一个UIScrollView
子类,因此您可以将自己设置为UIScrollViewDelegate
并获取滚动视图委托callback。
其中一个委托方法( -scrollViewDidScroll:
的参数是滚动的滚动视图,您可以将它与您的表视图进行比较,以确定它滚动的是哪一个。
对不起,我误解了你的问题。 我以为你想知道哪个表视图正在滚动(我错过了“方式”)。
要知道方向,你可以保留一个variables的前一个偏移量,看看delta(current.y – previous.y)是正值(向下滚动)还是负值(向上滚动)。
您可以跟踪内容偏移量的差异。 保持旧的一个成员/静态variables,并检查当前。 如果旧值低,则滚动向下,反之亦然。
override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if targetContentOffset.memory.y < scrollView.contentOffset.y { //println("Going up!") } else { // println("Going down!") } }
你可以通过这种方式实现UIScrollView
的委托方法来做到这一点,它是优雅的。
PS: lastOffset
和lastOffset
是ViewController的属性。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGPoint currentOffset = scrollView.contentOffset; self.scrollingUpward = currentOffset.y > self.lastOffset.y; self.lastOffset = currentOffset; }
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { if (yourTableView.isDragging || yourTableView.isDecelerating) { // your tableview is scrolled. // Add your code here } }
在这里你必须replace你的tableview名称而不是“yourTableView”。
yourTableView.isDragging – 如果用户已经开始滚动,则返回YES。 这可能需要一定的时间和/或距离才能启动。
yourTableView.isDecelerating – 如果用户没有拖动(触摸),则返回YES,但滚动视图仍在移动。