ios - 快速避免索引超出范围错误
问题描述
在我的 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
计数时,您需要在使用它下标之前numberOfItemsInSection
检查您的数组是否为空。cellForItemAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if movies.isEmpty {
//return your empty cell
}
else {
//access array element and return cell
}
}
推荐阅读
- python - Python C-API:如何在 Objective-C 中使用返回的 Python 字典?
- javascript - 在 vue js 和 laravel 中使用 v-for 进行迭代的问题
- azure - 用户和会话遥测
- java - java.lang.RuntimeException:找不到流“/files/myScript.py”
- python - 导入 Keras 时出错
- javascript - 如何将数组拆分为块,但让它一个接一个地填充每个数组
- ftp - Raspberry pi FTP 无法与 IP 摄像头一起使用
- tensorflow - 如何根据相应卷积层的训练值权重计算反卷积层的权重
- vuejs2 - 从 Vue 组件抛出异常并阻止任何进一步处理
- neural-network - 准确度值与我的 keras 模型的预测结果不匹配