Ios 在Swift中更改UICollectionView中的文本颜色
我有一个UICollectionView,其中的单元格包含动态更新的UILabel。当我选择一个单元格时,我会更改单元格的背景色,但我希望标签中的文本颜色也会更改。目前,我正在使用以下代码:Ios 在Swift中更改UICollectionView中的文本颜色,ios,swift,Ios,Swift,我有一个UICollectionView,其中的单元格包含动态更新的UILabel。当我选择一个单元格时,我会更改单元格的背景色,但我希望标签中的文本颜色也会更改。目前,我正在使用以下代码: func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { cell = collectionView.dequeueReusableCellWith
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()
}
但是,在选择单元格时,文本颜色不会更新为新颜色。知道为什么吗?因为您正在对一个可重用单元进行排队并更新它 基本上,dequeueReusableCellWithReuseIdentifier:forIndexPath:仅在collectionView:cellForItemAtIndexPath:中使用 使用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
}
}
因为您正在将可重用单元出列并更新它 基本上,dequeueReusableCellWithReuseIdentifier:forIndexPath:仅在collectionView:cellForItemAtIndexPath:中使用 使用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
}
}