首页 > 解决方案 > 无效更新:第 0 节中的项目数无效。数据源首先更新

问题描述

我已经阅读并查看了提到这一点的几篇文章。我尽力跟进,但我仍然遇到问题。

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)

标签: iosswiftcollectionviewindexpath

解决方案


您是否使用以下委托方法?您的代码非常有限,并没有提供太多信息。但是,我认为您正在尝试在不重新加载 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 中插入新项目。


推荐阅读