为什么方法didDeselectItemAt不调用?

问题描述

我有问题。 我在tableView中嵌入了一个集合视图。 我存储选定项目的indexPath(用于在重用单元格后还原其状态)。 问题是:当我选择项目时,向下滚动并向上滚动-我选择的项目处于存储状态,但是我不能取消选择项目。方法diddiselectItem不会调用

extension CategoryCollectionCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        items?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryCell.identefier,for: indexPath) as! CategoryCell
        let currentItem = items?[indexPath.row]
        cell.config(text: currentItem?.name ?? "")
        cell.isSelected = currentItem?.isSelected ?? false
        cell.layoutIfNeeded()
        return cell
    }
}

extension ImmoFilterCategoryCollectionCell: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
        items?[indexPath.row].isSelected = true
        delegate?.update(attributes: items,indexPath: self.indexPath)
    }
    
    func collectionView(_ collectionView: UICollectionView,diddeselectItemAt indexPath: IndexPath) {
        items?[indexPath.row].isSelected = false
        delegate?.update(attributes: items,indexPath: self.indexPath)
    }
}

delegate?.update-用于存储indexPath的方法

解决方法

 func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell,for: indexPath) as! Cell
        guard let currentItem = items?[indexPath.row] else { return cell}
        cell.config(text: currentItem.name )
        if  currentItem.isSelected {
            self.collectionView.selectItem(at: indexPath,animated: true,scrollPosition: .bottom)
            cell.isSelected = true
        }
        return cell
    }

这对我有用