I try to select multiple items in collectionCell, but if i tap many times for deselect cell i get an error Thread 1: Fatal error: Index out of range
On this line selectedTimeIntervalArray.remove(at: indexPath.item)
on indexPath.item == 1
.
How to avoid this error?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedCell = collectionView.cellForItem(at: indexPath)
if indexPath.item == 0 {
selectedBackgroundColor(cell: selectedCell!)
selectedTime = timeIntervalArray[indexPath.item]
selectedTimeLabel.text = "Время - \(selectedTime)"
selectedTimeIntervalArray.append(selectedTime)
} else if indexPath.item == 1 {
selectedBackgroundColor(cell: selectedCell!)
selectedTime2 = timeIntervalArray[indexPath.item]
selectedTimeIntervalArray.append(selectedTime2)
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let deselectedCell = collectionView.cellForItem(at: indexPath)
if indexPath.item == 0 {
deselectedBackgroundColor(cell: deselectedCell!)
selectedTime = ""
selectedTimeIntervalArray.remove(at: indexPath.item)
} else if indexPath.item == 1 {
deselectedBackgroundColor(cell: deselectedCell!)
selectedTime2 = ""
selectedTimeIntervalArray.remove(at: indexPath.item)
}
}