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

UICollectionView详解:4-代理协议方法简介

通过UICollectionView的代理协议UICollectionViewDelegate中定义的方法,可以捕获用户点击集合视图中单元格的行为,从而可以进行进一步处理。

与用户点击相关的代理方法

当用户点击集合视图中的单元格时,与UITableView类似,也会调用相关的代理方法,主要包括如下几个。

  • 单元格被选中时调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
  • 设置单元格是否能够被选中
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath;
  • 设置单元格item是否能够取消选中
(BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
  • 单元格item被取消选中时调用
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;

与单元格高亮显示相关的代理方法

  • 设置单元格是否能够高亮显示
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath;
  • 单元格为高亮状态时调用,只有当collectionView:shouldHighlightItemAtIndexPath:方法返回YES时,此方法才有用
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath;
  • 单元格取消高亮状态时调用
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath;