美文网首页
KVO监听scrollView的滚动方向

KVO监听scrollView的滚动方向

作者: yyggzc521 | 来源:发表于2019-04-17 17:17 被阅读0次
  1. 设置监听
[self.mainScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
  1. 监听回调处理
- (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];
    }
}
  1. 移除监听
- (void)dealloc
{
    [self.mainScrollView removeObserver:self forKeyPath:@"contentOffset"];
}

利用KVO来监听scrollView类contentOffset的变化

相关文章

网友评论

      本文标题:KVO监听scrollView的滚动方向

      本文链接:https://www.haomeiwen.com/subject/mtonwqtx.html