动态处理 UICollectionViewCell 元素中的背景色和前景色 [英] Dynamically handle the background and foreground colors inside UICollectionViewCell's elements
问题描述
我有一个 UICollectionViewCell
,其中包含一个 UIView
,其中包含一个 UILabel
.我必须根据布尔值更改 UIView
的背景颜色和 UILabel
的文本颜色.除非我在 UICollectionView
中添加第四项,否则基于布尔值的颜色会起作用.添加第四个项目后,所有先前和当前单元格中的所有项目都会获得与第四个单元格项目相同的各自颜色.
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.
问题与this 但在这里我无法在 UICollectionViewCell
的 >init 方法,然后根据布尔值在 cellForRowAt
中激活/停用它们.我该怎么做才能解决这个问题?
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?
推荐答案
在prepareForReuse中重置
自定义 UIView
和UILabel
的colors
()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
}
}
这篇关于动态处理 UICollectionViewCell 元素中的背景色和前景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!