Invalid update: invalid number of items on UICollectionView — How to solve this bug?

CodingRasi
3 min readJun 15, 2023

--

Just a meme

Hi everybody!

In this article I am going to share with you possible solution for a common bug that exists in UICollectionView.

But before, let me ask you my usual question:

Did you read my previous articles? 🤔 If not, then here they are: 👀

Ok, now let’s start with our main topic. 🧐

Another meme

Developers — all of us hate bugs, but keep in mind that if there is no bugs, then there is no work.

In iOS Development one of the most common bug is “Invalid update: invalid number of items on UICollectionView”.

All of us have seen this bug at least for once. If you did not see it yet, don’t worry, you will see it one day. 😉

I cannot show you wrong implementation here, because all of us have different way of implementing code, but if you faced with this bug, then here is one possible solution for you, thank me later. 😎

  1. Introduce a new variable:
var someNewVariable: Int = 0

2. Create following function || edit it:

  func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return someNewVariable
}

3. Call this appropriate place in your code:

 override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
updateItems.forEach { ourItem in
switch ourItem.updateAction {
case .add:
someInsertedIndex.append((item.indexPathBeforeUpdate, item.indexPathAfterUpdate))
someNewVariable += 1 // We define addition assignment operator.
case .delete:
someDeletedIndex.append((item.indexPathBeforeUpdate, item.indexPathAfterUpdate))
someNewVariable -= 1 // We define addition assignment operator.
default:
break
}
}
}

That will solve your problem. The third code block is just an example, please keep in mind that you should understand the logic and implement it properly in your project.

For further reading, at the very end of my article you will find useful links. 🙂

Yes, you might say that introducing new variable might create new bugs or it is a workaround — I respect your idea but I just disagree.

Oh you want to thank me: You have couple of options: clap, comment, share, follow or buy me a coffee. 🙂

Don’t forget to follow us on twitter. 🥳

Further reading:

https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617784-prepare

https://developer.apple.com/documentation/uikit/uicollectionviewupdateitem

--

--

CodingRasi
CodingRasi

Written by CodingRasi

I speak 6 human and 5 programming languages. 🥳  iOS Developer. To support me: https://codingrasi.com

No responses yet