iOS-UICollectionView cell设置背景图片

需求:

1.默认选中第一个cell
2.选中和没被选中的cell都有不同的背景图片。

实现步骤

  • 第一步,实现默认选中第一个cell:
    注意:一定要在UICollectionView加载完数据之后设置默认选中第一个cell
// 在我的项目中,我在网络加载完UICollectionView的数据之后写了以下几行代码
[self.collectionView reloadData];
            
// 设置默认选中第一个cell
[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:kNilOptions];
  • 第二步,在UICollectionViewDataSource代理方法中
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FKNetworkCardCvCell *cell = (FKNetworkCardCvCell *)[collectionView dequeueReusableCellWithReuseIdentifier:networkCardCellId forIndexPath:indexPath];
    
    // 这方法里面主要就是设置选中和没选中时,cell的背景图片
    [self updateCellStatus:cell selected:cell.isSelected];
    
    return cell;
}
  • 第三步,在UICollectionViewDelegate代理方法中
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 该cell networkCardCvCell已被选中
    FKNetworkCardCvCell *networkCardCvCell = (FKNetworkCardCvCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    [self updateCellStatus:networkCardCvCell selected:networkCardCvCell.selected];

}

// 该方法在你不选中某个cell的时候调用
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 该cell networkCardCvCell已被撤销选中
    FKNetworkCardCvCell *networkCardCvCell = (FKNetworkCardCvCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    [self updateCellStatus:networkCardCvCell selected:networkCardCvCell.selected];
}

总结

实现这个需求的方法有多种,但是笔者觉得这种做法是比较好的。省得写什么辅助属性。如果你有更好的方法,求分享哦!

你可能感兴趣的:(iOS-UICollectionView cell设置背景图片)