【问题标题】:ERROR: Attempt to insert item 0 into section 0, but there are only 0 items in section 0 after the update错误:尝试将第 0 项插入第 0 节,但更新后第 0 节中只有 0 项
【发布时间】:2016-11-24 03:35:42
【问题描述】:

我的代码:

    DataService.dataService.fetchDataFromServer { (channel) in
        self.channels.append(channel)
        let indexPath = IndexPath(item: self.channels.count - 1, section: 0)
        self.collectionView?.insertItems(at: [indexPath])
    }

从服务器函数获取数据:

 func fetchDataFromServer(callBack: @escaping (Channel) -> ()) {
        DataService.dataService.CHANNEL_REF.observe(.childAdded, with: { (snapshot) in
            let channel = Channel(key: snapshot.key, snapshot: snapshot.value as! Dictionary<String, AnyObject>)
            callBack(channel)
        })
    }

项目数部分:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return 0
}

完整的错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert item 0 into section 0, but there are only 0 items in section 0 after the update'

我正在使用集合视图,但不知道为什么会出现此错误。

任何帮助将不胜感激!

【问题讨论】:

  • 显示你的numberOfItemsInSection方法
  • 刚刚添加。去看看吧!
  • 你返回 0。你可能想返回 self.channels.count
  • 确保self.channels.count中有一些数据并且它的计数不是0
  • 你为collection view设置了delegate和data source了吗?

标签: ios swift uicollectionviewcell indexpath


【解决方案1】:

你的 numberOfItemsInSection 返回 0,所以当告诉集合视图你正在添加一个项目时,当这个方法说集合中仍然有 0 个项目时,它会感到不安。

您的代码甚至还有注释// #warning Incomplete implementation, return the number of items

你可能想要这样的东西:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return self.channels.count
}

【讨论】:

  • 不,这是根据您提供的信息列出的问题的解决方案。您是否仍然遇到同样的异常?
  • 是的,我仍然遇到同样的错误,所以它不起作用,你有其他解决方案吗,抱歉我的评论措辞不佳
  • 正如我所说,我无法根据您所展示的内容提出其他建议,但很有可能您还没有根据numberOfItemsInSection 中的代码设置其他内容跨度>
【解决方案2】:

我遇到了同样的问题,并修复了将 [unowned self] 放入闭包并强制 UI 更新在主线程上完成的问题。此外,正如其他人所说,numberOfItemsInSection 方法应该返回数组中的项目数。这是我的最终代码:

DataManager.fetchDish() { [unowned self] dish in
        if let dish = dish {
            DispatchQueue.main.async {
                self.dishes.append(dish)
                self.dishesCollectionView.insertItems(at: [IndexPath(row: self.dishes.count - 1, section: 0)])
            }
        }
    }

【讨论】:

    【解决方案3】:

    确保您连接了数据源,这让我很头疼,因为它非常基础,有时您根本不会考虑它。

    【讨论】:

      【解决方案4】:

      对于遇到此问题的其他用户,在尝试更新未分配 dataSource 的 TableView 或 CollectionView 时也会出现这些错误。确保 TableView 的 dataSource 已连接(使用情节提要或 nib 时)或以编程方式分配。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多