iOS学习笔记iOS开发iOS 开发每天分享优质文章

关联:添加观察者实现同步

2016-10-15  本文已影响0人  阿良天界

一,要求

1.关联的两个视图在同一个控制器里

2.将两个需要关联的View的头文件导入控制器

3.@interface FirestViewController ( ) 中子类化俩View

@property(nonatomic,strong)TopNavCollectiomView *topVC;

@property(nonatomic,strong)ContentCollectionView *contentVC;

二,创建观察者(这里以导航视图和内容视图关联实现同步为例)

在-(void)viewDidLoad方法中添加视图观察者

//给头部视图添加观察者

[self.topVC addObserver:self forKeyPath:@"currentItem" options:NSKeyValueObservingOptionNew context:nil];      //监听topVC中currentItem属性

//内容视图添加观察者

[self.contentVC addObserver:self forKeyPath:@"currentItem" options:NSKeyValueObservingOptionNew context:nil];

三,实现监听方法

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

NSNumber *newValue=change[@"new"];//接收监听变量的变化值

NSInteger item=[newValue integerValue];

NSIndexPath *indexPath=[NSIndexPath indexPathForItem:item inSection:0];

if (object==self.topVC &&self.contentVC.currentItem!=item) {

self.contentVC.currentItem=item;

//滑动到指定位置

[self.contentVC scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}else if (object==self.contentVC && self.topVC.currentItem!=item){

self.topVC.currentItem=item;

//滑动到指定位置

[self.topVC scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}

//刷新视图

[self.contentVC reloadData];

[self.topVC reloadData];

}

上一篇 下一篇

猜你喜欢

热点阅读