我使用 UIcollection View 作为我的标签栏 当我水平滚动 Collection View 时,当我选择新的单元格时,前一个选定的单元格不会取消选择
这是我选择一个单元格和取消选择一个单元格时改变颜色的代码
var selectedIndexPath : IndexPath = []
func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as?
BottomCollectionViewCell {
cell.contentView.backgroundColor = UIColor.orange
cell.backgroundColor = UIColor.orange
}
if let preViousSelectedcell = collectionView.cellForItem(at:
selectedIndexPath) as? BottomCollectionViewCell {
preViousSelectedcell.contentView.backgroundColor=UIColor.purple
preViousSelectedcell.backgroundColor = UIColor.purple
}
selectedIndexPath = indexPath
}
最佳答案
当滚动单元格被重用时 cellForItemAt
将调用,因此您需要更改代码中的一些修改
func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
selectedIndexPath = indexPath
YOUR_COLLECTION_VIEW.reloadData()
}
并在 collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
if indexPath == selectedIndexPath {
cell.contentView.backgroundColor=UIColor.purple
cell.backgroundColor = UIColor.purple
} else {
cell.contentView.backgroundColor = UIColor.orange
cell.backgroundColor = UIColor.orange
}
希望对你有帮助
关于ios UICollectionView 单元格选择和取消选择问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545220/