一个UIView中的两个UICollectionView如何实现联动效果

  • 原理
    利用监听的方法来实现一个UIView中的两个UICollectionView的联动效果。

  • 实现方法
    1.先在第一个UICollectionView创建一个要监听的值,监听第二个UICollectionView的当前页码

@property(nonatomic,assign)NSInteger currentIndex;

2.并在第一个UICollectionView中的代理方法中将页码传给currentIndex。

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    CGFloat offSetX = targetContentOffset->x;
    CGFloat itemWidth = 80;
    NSInteger pageWidth = itemWidth + 10;
    
    NSInteger pageNum = (offSetX + pageWidth/2)/pageWidth;
    
    targetContentOffset->x = pageWidth*pageNum;
    
    self.currentIndex = pageNum;
}

3.在UIView的.m文件中设置KVO的监听者

[smallCollectionV addObserver:self
                   forKeyPath:@"currentIndex" //监听的属性
                      options:NSKeyValueObservingOptionNew
                      context:nil];

4.在到最后面设置监听

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

    NSInteger index = [[change objectForKey:@"new"]integerValue];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0 ];
    [largeCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    
}

5.在到第二个UICollectionView的
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetContentOffset
代理方法中写以下代码:

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    CGFloat offSet = targetContentOffset->x;
    CGFloat width = KScreenWidth -100;
    
    NSInteger pageWidth = width + 50;
    NSInteger pageNum = (offSet + pageWidth/2)/pageWidth;
    targetContentOffset->x = pageWidth*pageNum;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:pageNum inSection:0 ];
    
    [smallCollectionV scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}
  • 实现的效果
13.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容