首页 > 解决方案 > 关闭视图控制器时在 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()
        }

    }

标签: iosswiftuitableviewuicollectionview

解决方案


正如你提到你想保存arrSelectedIndexuserdefault,所以arrSelectedIndexuserdefault。如果您在 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
    }


推荐阅读