1

我遇到 CollectionView 致命错误:使用 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 个单元格,我可以毫无问题地重新加载 de collectionView,但是当我添加另一个单元格时,导致 array.count 的单元格比视图显示的单元格多,刷新时出现错误。

错误是这一行

谢谢!

4

1 回答 1

1

您在cloudDataloadData() 调用的顶部设置了一个空数组,而不告诉集合视图重新加载。删除该行,无论如何您都将在 perform() 回调中替换数组的内容。

如果不重新加载集合视图,您将在集合视图和数据源之间创建不匹配,从而导致索引超出范围。

于 2017-10-09T14:58:05.190 回答