I have a UICollectionView
which I am trying to insert items into it dynamically/with animation. So I have some function that downloads images asynchronously and would like to insert the items in batches.
Once I have my data, I would like to do the following:
[self.collectionView performBatchUpdates:^{
for (UIImage *image in images) {
[self.collectionView insertItemsAtIndexPaths:****]
}
} completion:nil];
Now in place of the ***
, I should be passing an array of NSIndexPaths
, which should point to the location of the new items to be inserted. I am very confused since after providing the location, how do I provide the actual image that should be displayed at that position?
Thank you
UPDATE:
resultsSize
contains the size of the data source array, self.results
, before new data is added from the data at newImages
.
[self.collectionView performBatchUpdates:^{
int resultsSize = [self.results count];
[self.results addObjectsFromArray:newImages];
NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
for (int i = resultsSize; i < resultsSize + newImages.count; i++)
[arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
[self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
} completion:nil];
I was facing the similar issue while deleting the item from index and this is what i think we need to do while using
performBatchUpdates:
method.1# first call deleteItemAtIndexPath to delete the item from collection view.
2# Delete the element from array.
3# Update collection view by reloading data.
This help me to remove all the crash and assertion failures.
I just implemented that with Swift. So I would like to share my implementation. First initialise an array of NSBlockOperations:
In controller will change, re-init the array:
In the did change object method:
In the did change section method:
And finally, in the did controller did change content method:
I personally added some code in the deinit method as well, in order to cancel the operations when the ViewController is about to get deallocated:
See Inserting, Deleting, and Moving Sections and Items from the "Collection View Programming Guide for iOS":
So in your case, you must add an image to the collection view data source first and then call
insertItemsAtIndexPaths
. The collection view will then ask the data source delegate function to provide the view for the inserted item.