[英]Change background and label colour of UICollectionView cell when it is selected
[英]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()
不要依赖
isSelected
因为单元格已出列,当您滚动时,您会得到意想不到的结果
根据 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.