更新无效:第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)

解决方法

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

最好在下面做

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中插入新项目。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...