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

问题描述 投票:0回答:3

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

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

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

ios swift uicollectionview uicollectionviewcell
3个回答
6
投票

在vc中创建变量

var currentSelected:Int?

然后里面

cellForItemAt

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

终于

didSelectItemAt

currentSelected = indexPath.row
collectionView.reloadData()

不要依赖

isSelected
,因为单元格已出列,当您滚动时,您会得到意想不到的结果


1
投票

根据Apple关于单元格的backgroungView和选定的backgroungView的解释这里您应该在单元格类本身更改这些参数,并且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
}

0
投票

在您的收藏单元格中设置所选...

class CollectionCell: UICollectionViewCell {
        
        @IBOutlet weak var imageView: UIImageView!
        @IBOutlet weak var tagTitle: UILabel!
        
        override var isSelected: Bool {
            didSet {
                contentView.backgroundColor = isSelected ? .red : .white
            }
        }
        
        override func awakeFromNib() {
            super.awakeFromNib()
            
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.