我尝试在collectionCell中选择多个项目,但如果我多次点击取消选择单元格,我会收到错误 Thread 1: Fatal error: Index out of range
在这条selectedTimeIntervalArray.remove(at: indexPath.item)线上indexPath.item == 1。
如何避免这个错误?
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)
}
}