1、首先为UITableView添加观察者
[tableView addObserver: self forKeyPath: @"contentOffset" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil];
2、在KVO中,根据UITableView对象的相关属性,完成UITableView滚动方向的判断
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([object isKindOfClass: [UITableView class]]) {
CGPoint newPoint = [change[@"new"] CGPointValue];
CGPoint oldPoint = [change[@"old"] CGPointValue];
CGFloat newPointY = newPoint.y;
CGFloat oldPointY = oldPoint.y;
CGFloat frameHeight = ((UITableView *)object).frame.size.height;
CGFloat contentSizeHeight = ((UITableView *)object).contentSize.height;
// 这个地方把contentSizeHeight强制转为long类型很重要,因为本身它是CGFloat类型,所以可能会带有浮点数
// 一般我们在做表格的时候,实际上正数居多,为什么用long而不是int,主要是表示的整数范围会更大
if ((newPointY < oldPointY && (frameHeight + newPointY) < (long)contentSizeHeight) || newPointY < 0 || oldPointY < 0) {
if (newPointY <= 0 || oldPointY <= 0) {
NSLog(@"top");
} else {
NSLog(@"scroll down");
}
} else if (newPointY > oldPointY) {
if ((frameHeight + newPointY >= contentSizeHeight)) {
NSLog(@"bottom");
} else {
NSLog(@"scroll up");
}
}
}
}
网友评论