ios - 关闭视图控制器时在 UITableViewCell 中保存 UICollectionView 的选定状态
问题描述
如何保存UICollectionView
内部的选定状态UITableViewCell
?
有关更多详细信息,我有一个UITableView
包含 5 个部分的部分,每个部分只有一个单元格,我将另一个UICollectionView
放入表格视图的单元格中,每当我选择一个集合视图单元格的项目时,它都会以红色背景突出显示。
现在我想保存集合视图的选择状态,即使我关闭视图控制器然后再次打开它,它必须显示正确的选定项目,我想我将使用 UserDefaults 进行保存。但是我注意到,当我在另一个部分中选择一个集合视图项时,它总是保存与表视图的第一部分相同的索引。
这是我将所选索引路径保存到数组的代码,你能告诉我我的错误在哪里:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let strData = itemFilter[indexPath.section].value[indexPath.item]
let cell = collectionView.cellForItem(at: indexPath) as? SDFilterCollectionCell
cell?.filterSelectionComponent?.bind(title: strData.option_name!, style: .select)
cell?.backgroundColor = .red
cell?.layer.borderColor = UIColor.white.cgColor
arrSelectedIndex.append(indexPath)
}
当取消选择时:
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let strData = itemFilter[indexPath.section].value[indexPath.item]
let cell = collectionView.cellForItem(at: indexPath) as? SDFilterCollectionCell
cell?.filterSelectionComponent?.bind(title: strData.option_name!, style: .unselect)
cell?.backgroundColor = .white
cell?.layer.borderColor = UIColor.black.cgColor
if arrSelectedIndex.count > 0 {
arrSelectedIndex = arrSelectedIndex.filter({$0 != indexPath})
}else {
arrSelectedIndex.removeAll()
}
}
解决方案
正如你提到你想保存arrSelectedIndex
在userdefault
,所以arrSelectedIndex
从userdefault
。如果您在 UITableView 的每个部分都有 collectionView ,那么也arrSelectedIndex
保存indexpath
表部分。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.cellForItem(at: indexPath) as? SDFilterCollectionCell else {
return UICollectionViewCell()
}
// color the background accordingly
if arrSelectedIndex.contains(indexPath) {
// selected state
cell.backgroundColor = .red
} else {
// non-selected state
cell.backgroundColor = .white
}
cell.layer.borderColor = UIColor.white.cgColor
return cell
}
推荐阅读
- php - 使用 Laravel 的 Route URI 缺少路由参数?
- vb.net - gmail api突然返回403禁止
- java - "(...)+" 内的 javacc 扩展可以被空字符串错误匹配
- java - 正则表达式 Java 拆分逗号分隔的字符串,但忽略引号 + 大括号 + 递归括号内的逗号
- java - 注册jsp db后无法登录
- python - Reading in Files with Meaningful Whitespace (Python)
- django - 如何配置 VS Code 以使用 Prettier HTML 格式化程序?
- javascript - 使用 d3 js 按 id 选择元素的问题
- ionic-framework - Ionic 4 加载控制器
- swift - 为什么将对象的 y 位置设置为 UIScreen 的高度除以 2 而不是将其置于屏幕顶部?