垂直和水平滚动集合查看选择单元格问题

时间:2019-02-27 20:48:29

标签: swift collectionview

我有一个双向滚动collectionView,我希望单元格backgroundView在选中时显示,而在取消选中时消失。 我声明了一个带有选定indexPaths的数组,以便在cellForItemAt indexPath函数中对其进行测试,但是它不起作用。有任何帮助! 这是我的代码:

    var selectedIndexPaths:[IndexPath]=[]

 func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    if(selectedIndexPaths.contains(indexPath)){
        selectedIndexPaths=selectedIndexPaths.filter { $0 != 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
}

1 个答案:

答案 0 :(得分:0)

删除

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

在您选择一个单元格并自动取消选择先前选择的单元格后将其更改为

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

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