gpt4 book ai didi

ios - 如何避免错误index out of range?

转载 作者:可可西里 更新时间:2023-11-01 01:09:57 28 4
gpt4 key购买 nike

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

}

最佳答案

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

关于ios - 如何避免错误index out of range?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170210/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com