我的单元格在StoryBoard上设置为蓝色,但即使我在用户选择单元格时更改单元格backgroundColor,它们仍保持蓝色(不是红色)。我的代码出了什么问题?
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
不要在
dequeueReusableCell
中使用cellForItemAt
,因为它会返回一个不是被点击的单元格
当细胞不在这里时,可以调用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?
尝试在didDeselectItemAt上添加cell.backgroundColor = UIColor.clear。
像这样:
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "throneCell", for: indexPath) as! CharacterViewCell
let character = characters[indexPath.row]
cell.backgroundColor = UIColor.clear
onBoardingService.removeCharacter(character: character)
}