Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Swift中更改UICollectionView中的文本颜色_Ios_Swift - Fatal编程技术网

Ios 在Swift中更改UICollectionView中的文本颜色

Ios 在Swift中更改UICollectionView中的文本颜色,ios,swift,Ios,Swift,我有一个UICollectionView,其中的单元格包含动态更新的UILabel。当我选择一个单元格时,我会更改单元格的背景色,但我希望标签中的文本颜色也会更改。目前,我正在使用以下代码: func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { cell = collectionView.dequeueReusableCellWith

我有一个UICollectionView,其中的单元格包含动态更新的UILabel。当我选择一个单元格时,我会更改单元格的背景色,但我希望标签中的文本颜色也会更改。目前,我正在使用以下代码:

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