ios - CollectionView 在滚动时突出显示不正确的单元格

标签 ios objective-c

我有一个 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/

相关文章:

ios - 在搜索中包含文本

ios - 具有多语言支持的主题标签文本的正则表达式

iphone - 将顶点数组和面索引加载到 OpenGL-ES 中的最快方法?

ios - 协议(protocol)和委托(delegate)之间的区别?

ios - 如何从日期(2018-09-28 09 :42:00 +0000 ) without time in Date format - iOS swift?)中提取日、月和年(dd-MM-yyyy)

ios - 查看 Controller 更改选项卡栏图标和操作

ios - XCode 5.x + Maverick 在文件操作时崩溃

java - Xor 为 uint16 或 uint32 的字符串

objective-c - 是否可以在 Intellij IDEA 中突出显示 ObjC 代码?

objective-c - 无法让 Selector 为我的 Swift 函数工作