如何删除所有项目并将新项目添加到UICollectionView?

在某些事件上,

我想删除一个uicollectionview中的所有单元格,并添加新的单元格(这将作为networking调用的结果填充)

我试着用deleteItemsAtIndexPaths。 reloadSections,deleteSections / insertSections。

他们每个人都撞我的应用程序。

以下是我的代码。

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]; 

是的,正如Jonathan所说,我认为你想要做的是用新数据改变你的数据源,并简单地刷新或重新加载UICollectionView。

万一你需要一个比[collectionView reloadData]提供的animation更stream畅的animation,你可以使用插入和删除方法,这里是一个示例。

 -(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]; } }