CollectionView - 致命错误:索引超出范围 - 比视图更多的单元格可以显示
问题描述:
我有一个CollectionView致命错误:使用UIRefreshControl重新加载数据时索引超出范围。CollectionView - 致命错误:索引超出范围 - 比视图更多的单元格可以显示
集合被配置是这样的:
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return cloudData.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DataViewCell
// Configure the cell
cell.cloudDataPost = cloudData[indexPath.item]
return cell
}
重新加载数据的功能是这样的:
@objc func loadData() {
cloudData = [CKRecord]()
let publicData = CKContainer.default().publicCloudDatabase
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Data", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
publicWhisper.perform(query, inZoneWith: nil, completionHandler: { (results, error) in
if let datos = results {
self.cloudData = datos
DispatchQueue.main.async {
self.collectionView?.reloadData()
self.refresh.endRefreshing()
}
}
})
}
一切正常,只要细胞的数目小于所述视图可以显示。与4或7个单元格我可以重新加载de collectionView没有问题,但是当我添加另一个单元格导致array.count有更多的细胞比视图可以显示我刷新时出现错误。
谢谢!
答
您正在将cloudData
设置为loadData()调用顶部的空数组,而无需通知集合视图重新加载。删除该行,无论如何都要在perform()回调中替换数组的内容。
如果不重新加载集合视图,则会在集合视图和数据源之间创建不匹配,导致索引超出范围。
看起来像是将cloudData设置为loadData()调用顶部的空数组,而不告诉集合视图重新加载。删除该行,无论如何都要在perform()回调中替换数组的内容。 – Tim
谢谢你!这是整个问题! – rjgodoy
不客气:)我已将我的评论添加为答案。 – Tim