Ваша текущая реализация очень плохая.
Я бы посоветовал сохранить индекс выделенной ячейки как свойство и получить к нему доступ, чтобы выделять или не выделять, когда он отключается. Например:
// Your CollectionView Delegate class
var currentHighlightedCellIndex: Int?
Затем в вашем collectionView(_:cellForItemAt:)
:
// Dequeue the cell
...
if let selectedIndex = self.currentHighlightedCellIndex, selectedIndex == indexPath.row {
cell.selectedCell = true
} else {
cell.selectedCell = false
}
// Return the cell
...
В вашем collectionView(_:didSelectItemAt:)
:
guard let cell = collectionView.cellForItem(at: indexPath) as? YourCustomCellClass else { fatalError() }
cell.selectedCell = true
if let previouslySelectedIndex = self.currentHighlightedCellIndex {
// Here we get the index paths for each visible cell and check wether it's selected.
let indexPaths = collectionView.visibleCells.compactMap { collectionView.indexPath(for: $0) }
for index in (indexPaths.map { $0.item }) {
if index == previouslySelectedIndex {
// We found a cell that is highlighted and visible, get it in deselect it.
guard let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) else { fatalError() }
cell.selectedCell = false
}
}
}
self.currentHighlightedCellIndex = indexPath.item
Вы можете установить наблюдаемое свойство вкласс ячейки вашей пользовательской коллекции, который будет управлять цветом фона, например:
// Custom cell class
var selectedCell: Bool = false {
didSet {
self.mainView.backgroundColor = selectedCell ? .red : .white
}
}