首页 > 解决方案 > CollectionViewCell 在 didSelectItemAt 和 didDeselectItemAt 上更改颜色

问题描述

我正在显示一个集合视图,以便用户可以选择类别,然后我正在填充 TableView。

问题是,当集合单元格不可见时,didDeselectItemAt 函数没有响应。

这是我的代码:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    collectionView.cellForItem(at: indexPath)?.backgroundColor = UIColor.groupTableViewBackground
    let category = catgories[indexPath.row]
    setCategory(category: category)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    collectionView.cellForItem(at: indexPath)?.backgroundColor = UIColor.clear
}

标签: swiftuicollectionviewuicollectionviewcell

解决方案


那是因为 collectionView 中的单元格被重用了,您需要创建数组模型并跟踪每个单元格颜色并在里面分配它们cellForRowAt,这个

collectionView.cellForItem(at: indexPath)?.backgroundColor = UIColor.clear

nil indexPath 完全超出屏幕并验证是否执行此操作时

collectionView.cellForItem(at: indexPath)!.backgroundColor = UIColor.clear

应用程序将崩溃


推荐阅读