我的单元格在 StoryBoard 上设置为蓝色,但即使我在用户选择单元格时更改单元格背景颜色,它们仍然是蓝色(不是红色)。我的代码有什么问题?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "throneCell", for: indexPath) as! CharacterViewCell
let character = characters[indexPath.row]
cell.backgroundColor = UIColor.red
onBoardingService.pickCharacter(character: character)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "throneCell", for: indexPath) as! CharacterViewCell
let character = characters[indexPath.row]
onBoardingService.removeCharacter(character: character)
}
最佳答案
替换
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "throneCell", for: indexPath) as! CharacterViewCell
与
let cell = collectionView.cellForItem(at: indexPath) as! CharacterViewCell
Don't use
dequeueReusableCell
out ofcellForItemAt
as it'll return a cell that's not the clicked one
didDeselectItemAt
可能会在单元格不在此处时被调用,
guard let cell = collectionView.cellForItem(at: indexPath) as? CharacterViewCell else { return }
var selectedIndex = 0
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "throneCell", for: indexPath) as! CharacterViewCell
let character = characters[indexPath.row]
if selectedIndex == indexPath.row {
onBoardingService.pickCharacter(character: character)
cell.backgroundColor = UIColor.red
else {
cell.backgroundColor = UIColor.clear
onBoardingService.removeCharacter(character: character)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex = indexPath.row
collectionView.reloadData()
}
删除此方法
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "throneCell", for: indexPath) as! CharacterViewCell
let character = characters[indexPath.row]
onBoardingService.removeCharacter(character: character)
}
关于单项取消
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex = selectedIndex == indexPath.row ? nil : indexPath.row
collectionView.reloadData()
}
并声明
var selectedIndex:Int?
关于swift - 为什么我的收藏 View 单元格颜色选择不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681084/