在我的UICollectionView中,如果没有数据,我将尝试返回1项(以便设置空单元格)。以下是代码:
var movies = [Movies]()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if movies.count == 0 {
return 1
} else {
return movies.count
}
}
我得到致命的错误:索引超出范围。我知道,通过这种方式,我试图访问index1下的一个元素,这是不可能的,因为这个元素不存在,这就是这个错误的原因。
但在这种情况下我怎样才能避免呢?
发布于 2018-08-10 11:32:35
由于您要在numberOfItemsInSection
中返回空数组的numberOfItemsInSection
计数,您需要在订阅它之前检查您的数组是否为空的或不在cellForItemAt
中。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if movies.isEmpty {
//return your empty cell
}
else {
//access array element and return cell
}
}
https://stackoverflow.com/questions/51785555
复制相似问题