[英]Changing text color in UICollectionView in Swift
I have a UICollectionView with cells that contain UILabels that update dynamically. 我有一个包含包含动态更新的UILabel的单元格的UICollectionView。 When I select a cell, I have the background color of the cell change, but I want the text color in the label to change as well.
选择单元格时,单元格的背景颜色会发生变化,但是我希望标签中的文本颜色也发生变化。 Currently, I'm using the following code:
目前,我正在使用以下代码:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("targetCell", forIndexPath: indexPath) as UICollectionViewCell
var label : UILabel = cell.viewWithTag(100) as UILabel
label.textColor = UIColor.whiteColor()
}
However, on selecting the cell, the text color does not update with the new color. 但是,在选择单元格时,文本颜色不会更新为新颜色。 Any ideas why?
有什么想法吗?
Because you are dequeuing a reusable cell and update it. 因为您要使可重用单元出队并对其进行更新。
Basically, dequeueReusableCellWithReuseIdentifier:forIndexPath:
is only used in collectionView:cellForItemAtIndexPath:
. 基本上,
dequeueReusableCellWithReuseIdentifier:forIndexPath:
仅用于collectionView:cellForItemAtIndexPath:
。
Use cellForItemAtIndexPath
to get the selected cell. 使用
cellForItemAtIndexPath
获取选定的单元格。
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) {
let label = cell.viewWithTag(100) as? UILabel
label?.textColor = UIColor.white
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.