我有一个 UICollectionView
。当用户单击一个单元格时,该单元格的颜色变为红色。我已经对上面的部分进行了编码并且它工作得很好。
但是,当我向下滚动时, Collection View 中的其他单元格已突出显示为红色。我确信它没有被选中,而只是被突出显示。
我该如何解决。
我的代码如下:
cellForItemAtIndexPath 方法
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"cell";
ViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.vciv.image = [arrayOfImages objectAtIndex:indexPath.row];
return vc;
}
didSelectItemAtIndexPath 方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
if([items containsObject:allItem[indexPath.row]] ){
UICollectionViewCell *c =[collectionView cellForItemAtIndexPath:indexPath];
c.backgroundColor = [UIColor clearColor];
} else {
UICollectionViewCell *c =[collectionView cellForItemAtIndexPath:indexPath];
c.backgroundColor = [UIColor redColor];
}
最佳答案
随着 Collection View 单元格的重用,您需要确保在 cellForItemAtIndexPath:
方法中未突出显示已出队的单元格:
UICollectionViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.backgroundColor = [UIColor clearColor];
此代码将在出队时始终清除单元格的背景。如果需要保留突出显示,则需要存储要突出显示的单元格的 indexPath
,并检查当前单元格是否在该列表中。
编辑
看来您的 items
变量非常适合这样做。
所以你会这样做:
UICollectionViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.backgroundColor = [items containsObject:allItem[indexPath.row]] ? [UIColor redColor] : [UIColor clearColor];
关于ios - CollectionView 在滚动时突出显示不正确的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29097893/