ios - 无效更新:第 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 - 1
和self.collectionView.numberOfItems(inSection: 0)
解决方案
您是否使用以下委托方法?您的代码非常有限,并没有提供太多信息。但是,我认为您正在尝试在不重新加载 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 中插入新项目。
推荐阅读
- json - 如何在 Android Studio 中有效地编辑 json 文件?
- javascript - 在 Typescript 中创建倒计时的问题
- javascript - 替换类中包含某个单词的子div类
- javascript - 如何在reactjs中的map foreach中获取最后一个数据并设置颜色
- forms - 将行从表单响应移动到新选项卡,然后能够在完成后清除该响应
- php - 使用 PHP 和 LDAP-Active Directory 同步用户数据
- python - 如何在 Keras 中定义自定义 f1 指标
- db2 - 大数据批处理类图
- android - 拍照时出现TransactionTooLargeException
- javascript - 使用 javaScript 和 JAX-RS 的凭据