Заменить
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?