首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择UICollectionView的不可见细胞

选择UICollectionView的不可见细胞
EN

Stack Overflow用户
提问于 2017-06-02 19:07:26
回答 2查看 1.3K关注 0票数 0

我有一个UICollectionViewController,它使用自定义单元格。当用户点击一个单元格时,会调用一个函数,以区分选定的单元格,我将该单元格的背景色更改为绿色。问题是,当用户点击另一个单元时,应该取消对前一个单元格的选择,将调用另一个函数。只要没有滚动collectionView,它就能很好地工作,但是当用户滚动collectionView并选择一个从屏幕的可见区域走出来时,我的取消选择函数就不能工作了,并且会有两个带绿色背景的单元格。

这是演示:

你可以看到在顶部有一个绿色背景的细胞,在最后还有一个。

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

代码语言:javascript
复制
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
}
EN

回答 2

Stack Overflow用户

发布于 2017-06-02 19:18:49

我想,我得到了您的问题,简单地说,这是在滚动滚动视图之后发生的,这意味着所选的单元被选中,由于可重用的单元格自动被选中,这是一个常见的问题,它主要发生在UITableView和UIScrollView中。

在这个视图中,无论您在datasource中使用过datasource,还是它的delegate方法,都会放置一个else部分,这将解决您的问题。

例如:

代码语言:javascript
复制
    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
   }

希望这能帮到你。

票数 0
EN

Stack Overflow用户

发布于 2017-06-02 19:23:03

尝尝这个

代码语言:javascript
复制
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

    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44335864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档