KVO在我們的App的設(shè)置中用途非常廣泛,今天我們講的這個(gè)聯(lián)動(dòng)效果就需要用到KVO
1.在collectionView1 中設(shè)置頁碼,即每個(gè)cell的偏移值加派,然后運(yùn)用到代理方法
//將要結(jié)束拖拽(手指離開屏幕的的那一刻)
//該方法需要將pagingEnabled關(guān)掉才可以使用
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
NSLog(@"---------");
NSLog(@"滑動(dòng)的速度%lf",velocity.x);
NSLog(@"松手時(shí)x方向的偏移量:%lf",scrollView.contentOffset.x);
//targetContentOffset是個(gè)指針,可以修改參數(shù).
NSLog(@"目標(biāo)的最終的偏移量:%lf",targetContentOffset->x);
//1 根據(jù)偏移量判斷一下應(yīng)該顯示第幾個(gè)item
CGFloat offSetX = targetContentOffset->x;
CGFloat itemWidth =80;
//item的寬度+行間距 = 頁碼的寬度
NSInteger pageWidth = itemWidth+10;
//根據(jù)偏移量 計(jì)算是 第幾頁
NSInteger pageNum = (offSetX+pageWidth/2)/pageWidth;
NSLog(@"pageNumber= %ld",pageNum);
//2 根據(jù)顯示的第幾個(gè)item,從而改變偏移量
targetContentOffset->x = pageNum*pageWidth;
//設(shè)置currentIndex屬性叫确,接收這個(gè)頁碼
self.currentIndex = pageNum;
}
2.在collectionView2中設(shè)置觀察者
[smallCollectionV addObserver:self
forKeyPath:@"currentIndex" //監(jiān)聽的屬性
options:NSKeyValueObservingOptionNew context:nil];
3.改變collectionView2的item 即頁碼
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSInteger index = [[change objectForKey:@"new"]integerValue];
//轉(zhuǎn)成index
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
//實(shí)時(shí)轉(zhuǎn)換頁面
[largeCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
1
2