垂直和水平滚动 collectionView select 单元格问题

vertical and horizontal scroll collectionView select cell issue

我有一个双向滚动的 collectionView,我希望单元格 backgroundView 在选中时出现,在取消选中时消失。 我用选定的 indexPaths 声明了一个数组以在 cellForItemAt indexPath 函数中对其进行测试,但它没有 work.Any 请帮忙! 这是我的代码:

    var selectedIndexPaths:[IndexPath]=[]

 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    if(selectedIndexPaths.contains(indexPath)){
        selectedIndexPaths=selectedIndexPaths.filter { [=11=] != indexPath }
    } 
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedIndexPaths.append(indexPath)
 collectionView.reloadItems(at: [indexPath])
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // swiftlint:disable force_cast
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellIdentifier,
                                               for: indexPath) as! UserCollectionCell

    if(selectedIndexPaths.contains(indexPath) ){
        cell.backgroundView?.isHidden=false
    }
    else{
        cell.backgroundView?.isHidden=true
    }

    return cell
}

移除

 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    if(selectedIndexPaths.contains(indexPath)){
        selectedIndexPaths=selectedIndexPaths.filter { [=10=] != indexPath }
    } 
} 

当您 select 一个单元格并自动删除 select 之前 select 编辑的单元格时调用它,然后将其更改为

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if selectedIndexPaths.contains(indexPath) {
        selectedIndexPaths = selectedIndexPaths.filter { [=11=] != indexPath }
    }
    else {
       selectedIndexPaths.append(indexPath)
    }
    collectionView.reloadItems(at: [indexPath])
}