首页 > 解决方案 > 快速避免索引超出范围错误

问题描述

在我的 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] 下的元素,这是不可能的,因为该元素不存在,这就是这个错误的原因。

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

标签: iosswiftuicollectionview

解决方案


当您返回空数组的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
    }
}

推荐阅读