免费开源的iOS开发学习平台

UICollectionView详解:2-数据源协议DataSource

UICollectionView的数据源对象为集合视图的单元格Cell提供了数据,其基本使用方法与UITableView的数据源方法类似,但区别在于集合视图需要提前注册单元格Cell。

常用数据源方法

集合视图的数据源协议为UICollectionViewDataSource,其中定义了用于为集合视图中的单元格提供数据的相关方法。其中,如下两个方法是必须实现的方法。

  • 返回单元格个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
  • 根据indexPath属性,返回该单元格的具体样式和显示内容
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

另外,与表视图的数据源协议类似,我们还可以设置集合视图中包含的段Section数量。

  • 返回段Section个数,默认为1
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;
  • 设置头尾视图,同样也要先注册
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
  • 设置单元格是否可以移动
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);
  • 获取被移动单元格的原始位置与最新位置,移动单元格后调用,此方法用于更新数据源中的数据。
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0);

注册单元格

在集合视图中的单元格必须在创建集合视图时进行注册,单元格有两种注册方式,分别对应通过代码创建的单元格以及通过xib创建的单元格。

  • 通过代码创建出的单元格的注册方法
- (void)registerClass:(nullable Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
  • 通过xib创建出的单元格的注册方法
- (void)registerNib:(nullable UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;