我使用UIcollection视图作为我的tabbar 当我水平滚动集合视图时,当我选择新的
时,前一个选定的单元格将不会取消选择这是我选择单元格并取消选择单元格时更改颜色的代码
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
}
答案 0 :(得分:4)
当滚动单元格被重用时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
}
希望这会对你有所帮助