【发布时间】:2018-06-18 14:34:39
【问题描述】:
我尝试在 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)
}
}
【问题讨论】:
-
如果你将两个项目添加到一个数组中,然后 remove(at: 0),这个数组现在只包含一个项目,所以当你 remove(at: 1) 时它会崩溃。我建议寻找一种不同的方式来存储选定的状态。
-
你不想做
selectedTimeIntervalArray.remove(at: indexPath.item)。索引不是正确的。indexPath.item不是数组中对象的索引。相反,let index = timeIntervalArray.index(of:timeIntervalArray[indexPath.item]); timeIntervalArray.remove(at: index)
标签: ios swift xcode collections deselect