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

how to change cell background colour on selected item in UICollectionView and change other Cell colour to default in swift

我是 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

终于didSelectItemAt

currentSelected = indexPath.row
collectionView.reloadData()

Don't depend on isSelected as cells are dequeued and when you scroll you'll get unexpected results

根据 Apple 关于单元格的 backgroungView 和选定的背景视图的解释 Here 您应该在单元格 class 本身更改这些参数,并且 UICollectionView 将知道在单元格突出显示或选择时自动管理它:

override func awakeFromNib() {
  super.awakeFromNib()

  let redView = UIView(frame: bounds)
  redView.backgroundColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
  self.backgroundView = redView

  let blueView = UIView(frame: bounds)
  blueView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)
  self.selectedBackgroundView = blueView
}