CollectionView,改变单元格颜色

CollectionView, change Cell color

我有 collectionView,里面有 52 张图片,

关于 didSelectItemAtIndexPath 方法我有这个代码:

var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)! 
        cell.backgroundColor = UIColor.greenColor()

背景颜色正在改变,但是,当我向下滚动我的 collectionView 时,那里的另一个单元格有绿色背景颜色, 我假设 collectionView 做了一些重绘并且 indexPath 或其他东西发生了一些奇怪的事情,

真的可以使用有关如何仅更改一个单元格颜色的建议,即使在上下滚动集合视图时也是如此,

谢谢!

D

正在重复使用单元格。这就是原因。 在您的单元格 class 中,您应该在 prepareForReuse 方法中添加默认背景。 或者您可以在单元格中为 ItemAtIndexPath 设置背景。第一种方法更好。

已编辑

在您的 CustomCell.m 文件中:

-(void)setHighlighted:(BOOL)highlighted
{
if (highlighted)
{
    self.layer.opacity = 0.6;
    //or whatever you want here
}
else{
    self.layer.opacity = 1.0;
    //revert back the changes 
}
}

你可以开始了。

希望对您有所帮助:)

感谢 MKoosej 和其他人,

我成功了,

必须将方法添加到我的 customCell.swift:

override func prepareForReuse() {
        self.backgroundColor = UIColor.clearColor()
    }

然后在 cellForItemAtIndexPath 中,我检查存储 indexPath.row,如果它被选中然后我改变颜色。

现在滚动时可以使用了。

再次感谢,又学到新东西了!

丹尼斯