- 设置监听
[self.mainScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
- 监听回调处理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"contentOffset"]) {
NSValue *oldvalue = change[NSKeyValueChangeOldKey];
NSValue *newvalue = change[NSKeyValueChangeNewKey];
CGFloat oldoffset_y = oldvalue.UIOffsetValue.vertical;
CGFloat newoffset_y = newvalue.UIOffsetValue.vertical;
NSLog(@"Old:%f\nNew:%f",oldoffset_y,newoffset_y);
if (newoffset_y > oldoffset_y) {
NSLog(@"向下滑动");
} else if(newoffset_y < oldoffset_y) {
NSLog(@"向上滑动");
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- 移除监听
- (void)dealloc
{
[self.mainScrollView removeObserver:self forKeyPath:@"contentOffset"];
}
利用KVO来监听scrollView类contentOffset的变化
网友评论