如何更改 UICollectionView 中所选项目的单元格背景颜色并快速将其他单元格颜色更改为默认值

Muj*_*uju 1 ios uicollectionview uicollectionviewcell swift

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

if(cell.isSelected){
    cell.backgroundColor = UIColor.green
    }else{
       cell.backgroundColor = UIColor.clear
 }
Run Code Online (Sandbox Code Playgroud)

有什么方法可以仅将选定的单元格颜色更改为绿色,而将其他单元格颜色更改为清除 提前致谢!

Sh_*_*han 6

在vc中创建一个变量

var currentSelected:Int?
Run Code Online (Sandbox Code Playgroud)

然后里面cellForItemAt

cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear
Run Code Online (Sandbox Code Playgroud)

最后didSelectItemAt

currentSelected = indexPath.row
collectionView.reloadData()
Run Code Online (Sandbox Code Playgroud)

不要依赖isSelected单元格出队,当您滚动时,您会得到意想不到的结果