【问题标题】:vertical and horizontal scroll collectionView select cell issue垂直和水平滚动collectionView选择单元格问题
【发布时间】:2019-02-27 20:48:29
【问题描述】:

我有一个双向滚动的collectionView,我希望一个单元格背景视图在选中时出现,在取消选中时消失。 我声明了一个带有选定 indexPaths 的数组以在 cellForItemAt indexPath func 中对其进行测试,但它不起作用。请帮忙! 这是我的代码:

    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
}

【问题讨论】:

    标签: swift collectionview


    【解决方案1】:

    删除

     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])
    }
    

    【讨论】:

    • 使用您的解决方案,取消选择的单元格不会隐藏它的背景视图,直到您单击它,当您选择另一个单元格时它不会自动隐藏它
    猜你喜欢
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2011-01-12
    • 2014-01-09
    相关资源
    最近更新 更多