Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.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 如何在UICollectionView中更改选定项目的单元格背景颜色,以及如何在swift中将其他单元格颜色更改为默认值_Ios_Swift_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

Ios 如何在UICollectionView中更改选定项目的单元格背景颜色,以及如何在swift中将其他单元格颜色更改为默认值

Ios 如何在UICollectionView中更改选定项目的单元格背景颜色,以及如何在swift中将其他单元格颜色更改为默认值,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我是swift的新手,我正在尝试更改UICollectionView的单元格背景颜色,但它不起作用。我的代码在cellForItemAt中是这样的 if(cell.isSelected){ cell.backgroundColor = UIColor.green }else{ cell.backgroundColor = UIColor.clear } 有没有办法只将选定的单元格颜色更改为绿色,而将其他单元格颜色更改为透明 提前谢谢 在vc中创建一个变量 var

我是swift的新手,我正在尝试更改UICollectionView的单元格背景颜色,但它不起作用。我的代码在cellForItemAt中是这样的

if(cell.isSelected){
    cell.backgroundColor = UIColor.green
    }else{
       cell.backgroundColor = UIColor.clear
 }
有没有办法只将选定的单元格颜色更改为绿色,而将其他单元格颜色更改为透明
提前谢谢

在vc中创建一个变量

var currentSelected:Int?
然后在
cellForItemAt

cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear
currentSelected = indexPath.row
collectionView.reloadData()
最后
didSelectItemAt

cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear
currentSelected = indexPath.row
collectionView.reloadData()
不要依赖于
isSelected
,因为单元格已出列,当您滚动时,您将得到意外的结果


在vc中创建一个变量

var currentSelected:Int?
然后在
cellForItemAt

cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear
currentSelected = indexPath.row
collectionView.reloadData()
最后
didSelectItemAt

cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear
currentSelected = indexPath.row
collectionView.reloadData()
不要依赖于
isSelected
,因为单元格已出列,当您滚动时,您将得到意外的结果


无法在cellForItem中测试选定的。为所有单元格设置backgroundView并选择backgroundView。这回答了你的问题吗?无法在cellForItem中测试选定的。为所有单元格设置backgroundView并选择backgroundView。这回答了你的问题吗?