当我选择一个单元格时,它会变成蓝色,这很好。然后,当我向上滚动并且单元格不在视图中时,它会变回原始颜色。不知道如何解决这个问题。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor=[UIColor lightGrayColor];
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
self.collectionView.allowsMultipleSelection=YES;
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
datasetCell.backgroundColor = [UIColor blueColor];
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
}
答案 0 :(得分:2)
重复使用单元格时,选择状态将丢失。因此,您需要在didSelectItemAtIndexPath中保存选择的indexPath。当您将单元格出列时,需要检查并恢复状态
答案 1 :(得分:2)
在第一种方法中,您实际上是在告诉集合视图选择它要求的任何单元格。相反,你应该检查你返回的单元格是否与所选单元格具有相同的路径,然后才给它颜色:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
if ([indexPath isEqual:self.selectedIndexPath]) // you need to create selectedIndexPath as a property
{
cell.backgroundColor=[UIColor blueColor];
}
else
{
cell.backgroundColor=[UIColor lightGrayColor];
}
return cell;
}
然后:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedIndexPath = indexPath;
}