swift - 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
}
解决方案
那是因为 collectionView 中的单元格被重用了,您需要创建数组模型并跟踪每个单元格颜色并在里面分配它们cellForRowAt
,这个
collectionView.cellForItem(at: indexPath)?.backgroundColor = UIColor.clear
当nil
indexPath 完全超出屏幕并验证是否执行此操作时
collectionView.cellForItem(at: indexPath)!.backgroundColor = UIColor.clear
应用程序将崩溃
推荐阅读
- ruby-on-rails - DatabaseCleaner 在 :transaction 上失败
- spring-boot - Spring WebFlux OAuth2 JWT 配置
- python - USRP 未正确配置或硬件损坏?
- python - 创建渐变图例 matplotlib
- bash - 从文件中获取变量到另一个文件
- javascript - 反应:找不到模块:无法解析“/usr/src/app/src”中的“react-router-dom”
- sql - SQLite UNION ALL 和 Group by
- swift - 使导航栏隐藏swiftUI后如何忽略区域?
- javascript - React 组件继续渲染
- python-3.x - 在 pypi 上发布不同版本的库版本