·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS-scrollView与headerView的视差滚动实现思路

iOS-scrollView与headerView的视差滚动实现思路

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

假设场景: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暴露出来的接口就可以。