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

UICollectionView详解:5-代理方法实例

此示例主要是为了演示捕获用户点击集合视图中的单元格时,相关代理方法调用的时机,以及可以进行的进一步处理,如:跳转控制器等等。

  • 实现单元格被选中时的代理方法
//设置单元格能够选中
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//设置单元格能够取消选中
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//单元格被选中时调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s",__func__);
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];
}

//单元格被取消选中时调用
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s",__func__);
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
}
  • 实现单元格高亮状态显示相关的代理方法
//设置单元格能够高亮显示
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//单元格为高亮状态时调用
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s",__func__);
}

//单元格取消高亮状态时调用
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s",__func__);
}

当选中一个单元格时,会调用如下3个代理方法。

当选中另外一个单元格时,会调用如下4个代理方法,其中会取消之前第一次点击单元格的选中状态。

此时运行效果如下图所示。

示例代码

https://github.com/99ios/8.3.5