iOS 使用collectionview同时选中多个section分区的cell

iOS 使用collectionview同时选中多个section分区的cell_第1张图片
Untitled.gif

先来看一下用到的数据

- (void)initData{   
 _goodsArr = @[@"YSL", @"CHANEL", @"TF"];
    _colorsArr = @[@"12号色", @"52号色", @"400号色"];
    _payWaysArr = @[@"上个月工资", @"这个月工资", @"下个月"];
    _titleArr = @[@"送女朋友的品牌",@"色号",@"支付方式"];
    _allInfoArr = @[_goodsArr, _colorsArr, _payWaysArr];    
}

把每一个section中的数据 添加到了一个数组allInfoArr中 下面会用到哦

enm... 祝愿所有的你们都有机会送.

首先 初始化collectionview时候 把allowsMultipleSelection属性改为yes

   _collectionView.allowsMultipleSelection = YES;

在cellForItemAtIndexPath方法中 默认选中一个cell 这里默认选中了第0个

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:INDENTIFIE forIndexPath:indexPath];
      [collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    cell.nameStr = _allInfoArr[indexPath.section][indexPath.item];
    return cell;
}

选中后触发的方法didSelectItemAtIndexPath中

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //根据数据 把所有的都遍历一次 如果是当前点的cell 选中她 如果不是 就不选中她喽
    for (NSInteger i = 0; i < [[_allInfoArr objectAtIndex:indexPath.section] count];i++) {
        if (i == indexPath.item) {
            [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:indexPath.section] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
        }else {
            [self.collectionView deselectItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:indexPath.section] animated:YES];
        }
        
    }   
}

不选中cell的情况时候 didDeselectItemAtIndexPath中

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
   //如果点击了当前已经选中的cell  忽略她~
    [collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.item inSection:indexPath.section] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
}

你可能感兴趣的:(iOS 使用collectionview同时选中多个section分区的cell)