如何避免错误指数超出范围?

时间:2018-01-09 14:20:13

标签: ios swift xcode collections deselect

我尝试在 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)
    }

}

1 个答案:

答案 0 :(得分:2)

假设您选择indexPath.item == 1处的单元格。 你这样做

selectedTime2 = timeIntervalArray[indexPath.item]
selectedTimeIntervalArray.append(selectedTime2)

所以我们有:selectedTimeIntervalArray == ["ValueOfSelectedTime2"]

现在,我们取消选择该项目。 你那么做:

selectedTimeIntervalArray.remove(at: indexPath.item)

所以你在我们的案例中这样做:

selectedTimeIntervalArray.remove(at: 1)

索引1,真的吗?不,这会导致崩溃。因为selectedTimeIntervalArray只有一个项目,而且它位于索引0。

indexPath.item不是您存储在数组中的对象的index

相反,首先检索正确的索引:

let objectToRemove = timeIntervalArray[indexPath.item]‌
let index = selectedTimeIntervalArray.index(of: objectToRemove​)

然后删除它:

 selectedTimeIntervalArray.remove(at: index)