【问题标题】:Invalid update: invalid number of items in section 0. datasource updated first无效更新:第 0 节中的项目数无效。数据源首先更新
【发布时间】:2020-12-17 19:00:00
【问题描述】:

我已经阅读并查看了几篇提到这一点的帖子。我已尽力跟进,但仍有问题。

self.items.append(contentsOf: newItems)
let newIndexPath = IndexPath(item: self.items.count - 1, section: 0)
            
DispatchQueue.main.async {
    self.collectionView.insertItems(at: [newIndexPath])
 }

Items 是我拥有所有项目的数组,我正在添加 newItems。我做了一个打印,我知道有新项目。所以对于 newIndexPath 它将是下一个 items.count - 1。我尝试使用 self.items.count - 1self.collectionView.numberOfItems(inSection: 0)

【问题讨论】:

    标签: ios swift collectionview indexpath


    【解决方案1】:

    您是否使用以下委托方法?您的代码非常有限,并没有提供太多信息。但是,我认为您正在尝试在不重新加载 collectionView 数据的情况下更新 collectionView 部分中的项目数。

    最好在下面做:

    extension ViewController : UICollectionViewDataSource {
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return self.items.count
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
            else { fatalError("Unexpected cell in collection view") }
    
            cell.item = self.items[indexPath.row]
            return cell
        }
    

    如果您正在更新 items 数组,则追加新项目并重新加载 collectionView 将更新列表。你可以这样做:

    self.items.append(contentsOf: newItems)
    DispatchQueue.main.async {
       self.collectionView.reloadData()
    }
    

    无需在 collectionView 中插入新项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      相关资源
      最近更新 更多