【问题标题】:Invisible cells of UICollectionView stay selected [duplicate]UICollectionView 的不可见单元格保持选中状态[重复]
【发布时间】:2017-06-02 19:07:26
【问题描述】:

我有一个使用自定义单元格的 UICollectionViewController。当用户点击单元格时会调用一个函数,以区分所选单元格,我将单元格的背景颜色更改为绿色。 问题是,当用户点击另一个单元格时,应该取消选择前一个单元格,将调用另一个函数。只要 collectionView 不滚动它就可以正常工作,但是当用户滚动 collectionView 并选择一个超出屏幕的可见矩形时,我的取消选择功能不起作用,并且会有两个具有绿色背景的单元格。

这是演示:

您可以看到顶部有一个绿色背景的单元格,最后还有一个。

以下是选择和取消选择单元格的方法:

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

    if let cell = collectionView.cellForItem(at: indexPath) as? CategoryCollectionViewCell {
            cell.selectItem()
    }
}

override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
    for _cell in collectionView.visibleCells {
        if let __cell = _cell as? CategoryCollectionViewCell {
            __cell.deselectItem()
        }
    }

    if let indexPath = collectionView.indexPathsForSelectedItems {
        if indexPath.count > 0 {
            if let _cell = collectionView.cellForItem(at: indexPath.first!) as? CategoryCollectionViewCell {
                _cell.deselectItem()
            }
        }
    }

    return true
}

【问题讨论】:

  • 是多选吗?
  • @KKRocks 不,用户应该只选择一个单元格。
  • 好的,试试我的答案
  • “只要 collectionView 不滚动它就可以正常工作,但是当用户滚动 collectionView 时...” 看来您很可能遇到了问题,因为您正在修改单元格的属性,而不是数据源的属性。当您滚动 collectionView 时,将重新使用单元格。如果您不更新数据源,则滚动的单元格将不正确。

标签: ios iphone swift uicollectionview


【解决方案1】:

试试这个

let selectedIndexPath : IndexPath
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let cell = collectionView.cellForItem(at: indexPath) as? CategoryCollectionViewCell {
            cell.selectItem()
        }

        if let preViousSelectedcell = collectionView.cellForItem(at: selectedIndexPath) as? CategoryCollectionViewCell {
            preViousSelectedcell.deselectItem()
        }
        selectedIndexPath = indexPath

    }

【讨论】:

  • 是一样的。仍然选择了旧的选择。
  • 这种方法是正确的,你需要检查你是否得到了正确的上一个单元格。
【解决方案2】:

我想,我遇到了你的问题,这只是在滚动滚动视图后发生,这意味着选定的单元格被选中,并且由于可重复使用的单元格,另一个单元格被自动选中,这是一个常见问题,它发生在 UITableView 和 UIScrollView主要是。

在此视图中,无论您在datasource 中使用过if condition,其delegate 方法也放置了else 部分,这将解决您的问题。

例如:

    if let indexPath = collectionView.indexPathsForSelectedItems {
        if indexPath.count > 0 {
            if let _cell = collectionView.cellForItem(at: indexPath.first!) as? CategoryCollectionViewCell {
                _cell.deselectItem()
            }
        }
       else{
         // do something here
       }
    }
    else{
        // do something here
   }

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多