0

I have read and looked over the several posts that mentions this. I tried my best to follow along but I am still having an issue.

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

Items is the array where I have all of the items, I am adding newItems. I did a print and I know there is new items. So for newIndexPath it would be the next items.count - 1. I tried using self.items.count - 1 and self.collectionView.numberOfItems(inSection: 0)

1 Answers1

0

Are you using below delegates methods? Your code is very limited and doesn't give much information. However, I think you are trying to update the number of Items in section of collectionView without reloading the collectionView data.

Better to do below:

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
    }

If you are updating the items array, then append the new item and reload the collectionView will update the list. You can do as below:

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

No need to insert new item in collectionView.

Nandish
  • 1,136
  • 9
  • 16