在我使用 forin collectionView.visibleCells 将 cell.selected 设置为 NO 后,选择了其他它们会再次自动选择

After I use the forin collectionView.visibleCells to set the cell.selected to NO, selected other they are auto selected again

My collection view is like upper, when the selected cell all disappear I was invoke an action:

- (IBAction)clearAction:(UIButton *)sender {

    for (CustomCell *cell in self.buy_code_cv.visibleCells) {

        if (cell.selected) {
            [cell setSelected: NO];
        }

    }
}

在自定义单元格的 .m 文件中:我覆盖了 setSelected: 方法:

- (void)setSelected:(BOOL)selected {

    [super setSelected:selected];

    //self.selected = !selected;


    if (selected) {
        self.backView.backgroundColor = APP_COLOR;
        self.number_label.textColor = [UIColor whiteColor];
        self.multiple_label.textColor = [UIColor whiteColor];

    }
    // uncheck
    else {

        self.backView.backgroundColor = [UIColor whiteColor];
        self.number_label.textColor = HexRGB(0x999999);
        self.multiple_label.textColor = HexRGB(0xcccccc);
    }

    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedCustomCell:)]) {

        [self.delegate didSelectedCustomCell:self];
    }

}

如何解决 UICollectionView 中的这个问题?

A UICollectionViewCell 只是集合视图状态的一种表示,它不保存集合视图的状态。可以选择屏幕外的项目,在这种情况下甚至不会有该项目的 UICollectionViewCell 实例。

无需直接更新单元格,您需要告诉集合视图取消选择项目并让它负责更新屏幕上的所有单元格。

- (IBAction)clearAction:(UIButton *)sender {

    for (NSIndexPath *indexPath in self.buy_code_cv.indexPathForSelectedItems) {

        [self.buy_code_cv deselectItemAtIndexPath:indexPath animated:YES];

    }
}

我的建议是在 select 任何单元格时维护索引数组。 在这个方法中

 -(void)collectionView:(UICollectionView *)collectionView 
 didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
      if ([self.arraySelected containsObject:[NSNumber numberWithInt:indexPath.row]])
     {
           [self.arraySelected removeObject:[NSNumber numberWithInt:indexPath.row]];
     }
    else
    {
      [self.arraySelected addObject:[NSNumber numberWithInt:indexPath.row]];
    }

  [collectionView reloadData];
}

并且在这个方法中写这段代码

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{    
     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    if ([self.arraySelected containsObject:[NSNumber numberWithInt:indexPath.row]]) {
    self.backView.backgroundColor = APP_COLOR;
    self.number_label.textColor = [UIColor whiteColor];
    self.multiple_label.textColor = [UIColor whiteColor];

}
// uncheck
else {

    self.backView.backgroundColor = [UIColor whiteColor];
    self.number_label.textColor = HexRGB(0x999999);
    self.multiple_label.textColor = HexRGB(0xcccccc);
}
 return cell;
}