【问题标题】:how to change cell background colour on selected item in UICollectionView and change other Cell colour to default in swift如何在 UICollectionView 中更改所选项目的单元格背景颜色并在 swift 中将其他单元格颜色更改为默认值
【发布时间】:2021-03-25 23:46:00
【问题描述】:

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

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

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

【问题讨论】:

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

在vc里面创建一个变量

var currentSelected:Int?

然后在cellForItemAt里面

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

终于didSelectItemAt

currentSelected = indexPath.row
collectionView.reloadData()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2011-02-17
    相关资源
    最近更新 更多