【问题标题】:Avoid Index Out Of Range error in swift快速避免索引超出范围错误
【发布时间】:2023-03-09 08:55:02
【问题描述】:

在我的 UICollectionView 中,如果没有数据,我会尝试返回 1 项(以便设置一个空单元格)。 代码如下:

    var movies = [Movies]()

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if movies.count == 0 {
        return 1
    } else {
        return movies.count
    }
}

我收到致命错误:索引超出范围。我知道,这样我试图访问 index[1] 下的元素,这是不可能的,因为该元素不存在,这就是这个错误的原因。

但是在这种情况下我该如何避免呢?

【问题讨论】:

  • 在这个函数中你说...如果我没有项目...告诉集合视图我有 1 个项目。如果您只是在这里返回movies.count,您的问题就会消失。另外......你的崩溃不在这里......它在其他地方。

标签: ios swift uicollectionview


【解决方案1】:

当您返回 1 count in numberOfItemsInSection 时,您需要在下标之前检查cellForItemAt 中的数组是否为空。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if movies.isEmpty {
        //return your empty cell
    }
    else {
        //access array element and return cell
    }
}

【讨论】:

  • 哦,我在声明我的 2 个单元格,然后作为回报,我想: return movies.count == 0 ? emptyCell : cell 我想知道为什么这不起作用,但无论如何.. 你的案例工作了非常感谢!
  • @EmmaVagradyan 欢迎朋友 :)
  • @EmmaVagradyan 只是想知道,如果您使用的是 return movies.count == 0 ? emptyCell : cell,那么它也应该可以工作。
  • @KamaldeepsinghBhatia 不,不要在那个地方使用三元运算符,但你可以在 numberOfItemsInSection 使用它,就像这样 return movies.isEmpty ? 1 : movies.count
  • 哦,是的...谢谢@NiravD
猜你喜欢
  • 2018-06-18
  • 2023-04-07
  • 2021-01-27
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多