我有一个 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
}
答案 0 :(得分:0)
我想,我得到了你的问题,只是在滚动滚动视图后发生这种情况,这意味着所选内容被选中,并且由于可重复使用的单元格,另一个单元格会自动被选中,这是一个常见问题,它发生在UITableView和UIScrollView中居多。
在此视图中,只要您在if condition
中使用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
}
希望这可以帮助你。
答案 1 :(得分:0)
试试这个
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
}