On certain events,
I'd like to remove all cells in a uicollectionview, and add new cells.(which will be populated as a result of a network call)
I tried using deleteItemsAtIndexPaths. reloadSections, deleteSections/insertSections.
Each of them crashed my app.
Below is my code.
NSMutableArray* indexPathArray = [[NSMutableArray alloc] init];
for(int i=0; i < [self.jsonAlbumImageArray count]; ++i)
{
NSIndexPath* newPath = [NSIndexPath indexPathForRow:i inSection:0];
[indexPathArray addObject: newPath];
}
[self.jsonAlbumImageArray removeAllObjects];
if(indexPathArray.count > 0 )
{
[self.collectionView performBatchUpdates:^{
[self.collectionView deleteItemsAtIndexPaths:indexPathArray];
}
completion: nil];
}
// NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 1)];
// NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:0];
// [self.collectionView reloadSections:indexSet];
[self get_IMAGE_LIST_FROM_SERVER];
Just in case you need a smoother animation than the one provided by [collectionView reloadData] you can do it with the insert and delete methods, here is a sample.
-(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray *)itemPaths
{
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSIndexPath *itemPath in itemPaths) {
[indexSet addIndex:itemPath.row];
}
[self.apps removeObjectsAtIndexes:indexSet];
}
-(void)insertItems:(NSArray*)items ToDataSourceAtIndexPaths:(NSArray *)itemPaths
{
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSIndexPath *itemPath in itemPaths) {
[indexSet addIndex:itemPath.row];
}
[self.apps insertObjects:items atIndexes:indexSet];
}
-(void)reloadDataSmooth{
[self.collectionView performBatchUpdates:^{
NSMutableArray *arrayWithIndexPathsDelete = [NSMutableArray array];
NSMutableArray *arrayWithIndexPathsInsert = [NSMutableArray array];
int itemCount = [self.items count];
for (int d = 0; d<itemCount; d++) {
[arrayWithIndexPathsDelete addObject:[NSIndexPath indexPathForRow:d inSection:0]];
}
[self deleteItemsFromDataSourceAtIndexPaths:arrayWithIndexPathsDelete];
[self.collectionView deleteItemsAtIndexPaths:arrayWithIndexPathsDelete];
int newItemCount = [newItems count];
for (int i=0; i<newAppCount; i++) {
[arrayWithIndexPathsInsert addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[self insertItems:newItems ToDataSourceAtIndexPaths:arrayWithIndexPathsInsert];
[self.collectionView insertItemsAtIndexPaths:arrayWithIndexPathsInsert];
}
completion:nil];
}
}
Yeah, as Jonathan said, I think what you want to do is change your datasource with the new data and simply "refresh" or reload the UICollectionView.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With