集合视图单元格多项select错误

我有一个集合视图,我想select多个项目。 为此,我正在使用

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { [self.selectedAsset addObject:self.assets[indexPath.row]]; UICollectionViewCell* cell=[self.collectionView cellForItemAtIndexPath:indexPath]; cell.contentView.backgroundColor = [UIColor blackColor]; } 

此方法将对象添加到selectedAsset NSMutableArray。

这是cellForItemAtIndexPath方法。

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; { Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath]; // load the asset for this cell ALAsset *asset = self.assets[indexPath.row]; CGImageRef thumbnailImageRef = [asset thumbnail]; UIImage *thumbnail = [UIImage imageWithCGImage:thumbnailImageRef]; // apply the image to the cell cell.imageView.image = thumbnail; [cell.label removeFromSuperview]; //cell.imageView.contentMode = UIViewContentModeScaleToFill; return cell; } 

我使用这个代码偶然的背景颜色的单元格。

 UICollectionViewCell* cell=[self.collectionView cellForItemAtIndexPath:indexPath]; cell.contentView.backgroundColor = [UIColor blackColor]; 

但是,当我在“集合视图”中select第一个项目时,“集合视图”中的第1和第15个项目都会更改背景颜色。

为什么会发生? 请有人给我一个解决scheme。

好的,这似乎是你的问题。

1)当你select第一个单元格时,这个方法被调用

  - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 

在这种方法中,您将单元格背景颜色更改为黑色,因此此单元格从现在开始为黑色。

2)向下滚动,新的单元格加载方法

  -(UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; 

实施中有一条棘手的线路

 dequeueReusableCellWithReuseIdentifier: 

因此,对于新的单元格,您的应用程序可能不会创build新的单元格,而是显示不可见的单元格,例如您在开始时select的单元格1,以及具有黑色背景颜色的单元格。

所以对于新的单元格,您的应用可能会重复使用可能会被修改的旧单元

我的修补程序将是下一个 –

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath; { UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath]; //line below might not work, you have to tune it for your logic, this BOOL needs to return weather cell with indexPath is selected or not BOOL isCellSelected = [self.selectedAsset containsObject:self.assets[indexPath.row]]; if(!isCellSelected) { UICollectionViewCell* cell=[cv cellForItemAtIndexPath:indexPath]; cell.contentView.backgroundColor = [UIColor clearColor]; // or whatever is default for your cells } // load the asset for this cell ALAsset *asset = self.assets[indexPath.row]; CGImageRef thumbnailImageRef = [asset thumbnail]; UIImage *thumbnail = [UIImage imageWithCGImage:thumbnailImageRef]; // apply the image to the cell cell.imageView.image = thumbnail; [cell.label removeFromSuperview]; //cell.imageView.contentMode = UIViewContentModeScaleToFill; return cell; }