[英]Save selected state of UICollectionView inside UITableViewCell when dismiss the view controller
如何在UITableViewCell
保存UICollectionView
的選定狀態?
有關更多詳細信息,我有一個包含 5 個部分的UITableView
,每個部分只有 1 個單元格,我將另一個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
,因此從userdefault
獲取arrSelectedIndex
。 如果您在 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.