Dynamically handle the background and foreground colors inside UICollectionViewCell's elements

孤人 提交于 2019-12-25 02:33:44

问题


I have a UICollectionViewCell which contains a UIView enclosing a UILabel. I have to change the background color of UIView and the text color of UILabel on the base of a boolean value. The colors on the base of the boolean value work find unless I add the fourth item in the UICollectionView. All items from all previous and current cells get the same respective color like that of the items of the fourth cell as soon as I add the fourth item.

The problem is exactly related to this but here I cannot add the colors in the init method of UICollectionViewCell and then activate/deactivate them in cellForRowAt on the basis of the boolean value. What could I do to resolve this?


回答1:


Reset the colors of UIView and UILabel in prepareForReuse() method of your custom UICollectionViewCell.

Example:

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
    }
}


来源:https://stackoverflow.com/questions/56649158/dynamically-handle-the-background-and-foreground-colors-inside-uicollectionviewc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!