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

来源:互联网 时间:2017-01-22



原理
利用监听的方法来实现一个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



相关阅读:
Top