iOS

假设场景:viewController里面有一个scrollView,该scrollView有一个headerView。现在需要将scrollView的滚动contentOffset与headerView的变化联系起来,实现headerView跟随scrollView的contentOffset动态变化的效果。


1、自定义headerView:

  (1)使用一个指针接收viewController里面的scrollView。

  (2)重写willMoveToSuperview,使用KVO模式,为上述scorllView绑定一个Observer

    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:(NSKeyValueObservingOptionNew) context:nil];设置监听者为headerView本身

  (3)其中headerView监听函数为

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    CGPoint newOffset = [change[@"new"] CGPointValue];

    [self updateSubViewsWithScrollOffset:newOffset];

}

这样,在headerView里面可以实时得到scrollView的滚动contentOffSet,就可以做出与scrollView的contentOffset关联的动画效果。

2.viewController里面只需要将scrollView赋值给headerView暴露出来的接口就可以。

原文地址:https://www.cnblogs.com/boch2436/p/3526898.html