首页 > 解决方案 > 动态处理 UICollectionViewCell 元素内的背景和前景色

问题描述

我有一个UICollectionViewCell包含一个UIView封闭的 a UILabel。我必须在布尔值的基础上更改背景颜色UIView和文本颜色。UILabel除非我在UICollectionView. 一旦我添加了第四个项目,来自所有先前和当前单元格的所有项目都会获得与第四个单元格的项目相同的相应颜色。

问题与此完全相关, 但在这里我不能在init方法中添加颜色,UICollectionViewCell然后cellForRowAt根据布尔值激活/停用它们。我能做些什么来解决这个问题?

标签: iosswiftuicollectionviewuicollectionviewcell

解决方案


重置自定义的colorsofUIViewUILabelinprepareForReuse()方法UICollectionViewCell

例子:

class CustomCell: UICollectionViewCell {
    @IBOutlet weak var customView: UIView!
    @IBOutlet weak var label: UILabel!

    override func prepareForReuse() {
        super.prepareForReuse()

        //reset the colors here.........
        customView.backgroundColor = .white
        label.textColor = .black
    }
}

推荐阅读