UICollectionView 设置section的背景色

  • 使用tableview时,我们可以随意设置Tableview中每个Section的背景颜色而在UICollectionView中。系统并没有给我们提供一个现成的代理方法或者是属性来设置。为collectionView设置需要自己去自定义。需要在系统的流式布局UICollectionViewFlowLayout的基础上进行自定义。在网上找到了一个Swift版本的的。在此基础上进行修改完成了个OC版的Demo,写下备用。也可以留给有需要的人。
  • 使用方式:可以使用github上的ULBCollectionViewFlowLayout。在控制器中遵守ULBCollectionViewDelegateFlowLayout协议。在创建CollectionView时使用ULCollectionViewFlowLayout样式的layout,因为ULCollectionViewFlowLayout继承与UICollectionViewFlowLayout,多提供了下面的代理方法:
- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout colorForSectionAtIndex:(NSInteger)section;
  • Tips:collectionView在显示的时候没有问题。但是当你进行collectionView删除时,当section删除了最后一个item时就会奔溃。所以需要在代码使用时加上保护。参照stackoverflow在collectionView使用的代理时进行修改可以暂时解决奔溃问题,如下:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if(self.dataSoruces.count>0){ return 1; }
    else{ return 0; }
}
  • 在删除item时。加上判断,如果删除item之后,section中的
[   self deleteItemsFromDataSourceAtIndexPaths:selectedIndexes];

    if(idShadeInside.count > 0){
        [self.cv deleteItemsAtIndexPaths:selectedIndexes];
    }
    else{
        //Creating an IndexSet with the Section to Erase
        NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];[indexSet addIndex:0];
        [self.cv deleteSections:indexSet];
    }

ps:以上我是基于一个section的基础上添加。多个section的话。自己可以进行判断。以上。

猜你喜欢

转载自blog.csdn.net/yuwuchaio/article/details/76032880