Acey
Acey

Reputation: 8106

Inserting the first cell into a collection view causes an assertion failure

If I try to insert an item into a UICollectionView when there are 0 sections and 0 items, I get an assertion failure.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the collection view after the update (1) must be equal to the number of sections contained in the collection view before the update (0), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

A classic. The problem is, I'm modifying my data source and then inserting the item directly afterwards. The showFirstCell property is checked in all of the necessary data source methods and it isn't modified anywhere else.

self.showFirstCell = true
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: 0, inSection: 0)])

Wrapping this in performBatchUpdates changes nothing.

I would like for this item to be added in an animated fashion. I don't think I should have to first check if there are items already in place, but doing so and calling reloadData instead does work, but it's not perfect.

Upvotes: 0

Views: 194

Answers (3)

handiansom
handiansom

Reputation: 783

If you want to insert item from your CollectionView, you need to insert that item from your data source which is in your array. In this example I inserted the item to myArray then I inserted it also to myCollectionView. It's working because the total number of items from your array (data source) is equal to the number of items in the collectionView.

myArray.insert(valuetoinsert, atIndex: 0)
let path:NSIndexPath = NSIndexPath.init(row: 0, section: 0)
myCollectionView.insertItems(at: [path as IndexPath])

Upvotes: -1

user4645956
user4645956

Reputation:

The reason why it didn't work and gave you an error is because your numberOfSections is set to 0 and it didn't update yet when you add the cell.

To fix that, just create (if you don't have already) an NSMutableArray, and for numberofSections, return that mutableArray. Then whenever you add an object to the collectionView, just add an object to the mutableArray of sections.

Next and most important part is: Anytime you change, add, or remove something from the collectionView, just do a beginUpdat and endUpdate.

Upvotes: 0

Shamas S
Shamas S

Reputation: 7549

Your number of sections don't match up.

Once you have decided to enter a section to the UICollectionView, you should return the same number in your numberOfSections function as well.

What's happening right now is that you insert a cell, and it calls your numberOfSections function again, where you are still returning 0, and it promptly crashes.

Upvotes: 1

Related Questions