UICollectionView实现多选且组内单选

1、设置UICollectionView可以多选:self.collectionV.allowsMultipleSelection = YES;
2、在数据模型中添加select属性作为记录状态,添加indexPath属性作为拿去对应的Cell
3、取消选中:[collectionView deselectItemAtIndexPath:skut.indexPath animated:YES];
4、选中:[collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
5、获取所有选中的:NSArray * selectIndexPaths = collectionView.indexPathsForSelectedItems;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
CommodityTypeCell * cell = (CommodityTypeCell*)[collectionView cellForItemAtIndexPath:indexPath];
[cell setBackgroundColor:[UIColor grayColor]];
if (collectionView.indexPathsForSelectedItems.count!=self.commodity.proAttributeList.count) {
// 做对应的业务处理(比如商品分类标签,改为显示价格区间)
}
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
// 取消当前组内已选中的
CommodityType * type = self.commodity.proAttributeList[indexPath.section];
for (SkuList * skut in type.attribute_vals) {
if (skut.select == YES) {
skut.select = NO;
CommodityTypeCell * oldCell = (CommodityTypeCell*)[collectionView cellForItemAtIndexPath:skut.indexPath];
[oldCell setBackgroundColor:[UIColor grayColor]];
[collectionView deselectItemAtIndexPath:skut.indexPath animated:YES];// 取消选中
}
}
// 选中当前点击的item
SkuList * sku = type.attribute_vals[indexPath.item];
sku.select = YES;
sku.indexPath = indexPath;
CommodityTypeCell * cell = (CommodityTypeCell*)[collectionView cellForItemAtIndexPath:indexPath];
[collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];// 需要添加选中
[cell setBackgroundColor:[UIColor orangeColor]];
if (collectionView.indexPathsForSelectedItems.count!=self.commodity.proAttributeList.count) {
// 做对应的业务处理(比如商品分类标签,显示该商品的唯一价格和库存)
}
}

打赏支持一下呗!