代码之家  ›  专栏  ›  技术社区  ›  rjgodoy

CollectionView-致命错误:索引超出范围-超出视图显示的单元格数

  •  1
  • rjgodoy  · 技术社区  · 7 年前

    我遇到了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个单元格,我可以毫无问题地重新加载反收集视图,但当我添加另一个单元格时,会产生数组。count的单元格数超过了视图显示的单元格数,刷新时出现错误。

    The error is this line

    谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Tim    7 年前

    您正在设置 cloudData 调用loadData()顶部的空数组,而不告诉集合视图重新加载。去掉这一行,您将在perform()回调中替换数组的内容。

    如果不重新加载集合视图,则会在集合视图和数据源之间创建不匹配,从而导致索引越界。