【问题标题】:Save selected state of UICollectionView inside UITableViewCell when dismiss the view controller关闭视图控制器时在 UITableViewCell 中保存 UICollectionView 的选定状态
【发布时间】:2020-01-01 09:50:55
【问题描述】:

如何将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()
        }

    }

【问题讨论】:

    标签: ios swift uitableview uicollectionview


    【解决方案1】:

    正如您所说,您想将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
        }
    
    

    【讨论】:

    • 这就是我现在正在做的事情。但正如我所说,保存的 indexPath 是错误的。例如,如果我将UICollectionView 中的一个indexPath 保存在UITableView 的第0 部分中,则其他表格视图部分中具有相同indexPath 的所有项目也将显示为选中状态。
    猜你喜欢
    • 1970-01-01
    • 2016-10-22
    • 2014-09-10
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多