【问题标题】:How to avoid mistakes index out of range?如何避免错误索引超出范围?
【发布时间】: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


【解决方案1】:

假设您选择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)

【讨论】:

  • 谢谢,我明白了。它帮助了我。
猜你喜欢
  • 2023-03-09
  • 2023-04-07
  • 2016-07-22
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多