CollectionView Fatal error: Index out of range が UIRefreshControl でデータをリロードするときに発生します。
コレクションは次のように構成されます。
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 つのセルを使用すると、collectionView を問題なくリロードできますが、別のセルを追加すると、array.count にビューが表示できるよりも多くのセルが表示され、更新中にエラーが発生します。
ありがとう!