我有一个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
}发布于 2017-06-02 19:18:49
我想,我得到了您的问题,简单地说,这是在滚动滚动视图之后发生的,这意味着所选的单元被选中,由于可重用的单元格自动被选中,这是一个常见的问题,它主要发生在UITableView和UIScrollView中。
在这个视图中,无论您在datasource中使用过datasource,还是它的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
}希望这能帮到你。
发布于 2017-06-02 19:23:03
尝尝这个
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
}https://stackoverflow.com/questions/44335864
复制相似问题