简体   繁体   English

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

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

I am new in swift and I am trying to change cell background colour of UICollectionView but its not working my code is like this in cellForItemAt我是 swift 的新手,我正在尝试更改 UICollectionView 的单元格背景颜色,但它不起作用我的代码在 cellForItemAt 中是这样的

if(cell.isSelected){
    cell.backgroundColor = UIColor.green
    }else{
       cell.backgroundColor = UIColor.clear
 }

Is there is any way to change only selected cell colour to green and other cell to clear Thanks in Advance!有没有办法只将选定的单元格颜色更改为绿色,并将其他单元格颜色更改为清除提前谢谢!

Create a variable inside the vc在vc里面创建一个变量

var currentSelected:Int?

then inside cellForItemAt然后在cellForItemAt

cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear

finally didSelectItemAt终于didSelectItemAt

currentSelected = indexPath.row
collectionView.reloadData()

Don't depend on isSelected as cells are dequeued and when you scroll you'll get unexpected results不要依赖isSelected因为单元格已出列,当您滚动时,您会得到意想不到的结果

According to Apple's explanation about cell's backgroungView and selected backgroundView Here you should change those parameters at the cell class itself and the UICollectionView will know to manage it automatically when the cell is highlighted or selected:根据 Apple 关于单元格 backgroungView 和选定背景视图的解释, 应该在单元格 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM