问题描述
我已阅读并查看了提及此问题的几篇文章。我尽力跟进,但仍然遇到问题。
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部分中的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中插入新项目。