我正在尝试向现有UICollectionView
添加更多单元格,现有reloadData
已经填充了一些单元格。
我尝试使用CollectionView {{1}},但似乎重新加载整个collectionView,我只想添加更多单元格。
有人能帮助我吗?
答案 0 :(得分:6)
UICollectionView
类具有添加/删除项目的方法。例如,要在某个index
处插入项目(在0
部分中),请相应地修改您的模型,然后执行:
int indexPath = [NSIndexPath indexPathForItem:index];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath inSection:0];
[collectionView insertItemsAtIndexPaths:indexPaths];
视图将完成其余的工作。
答案 1 :(得分:5)
将新单元格插入 UICollectionView 而不必重新加载其所有单元格的最简单方法是使用 performBatchUpdates ,这可以通过以下步骤轻松完成
// Lets assume you have some data coming from a NSURLConnection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *erro)
{
// Parse the data to Json
NSMutableArray *newJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// Variable used to say at which position you want to add the cells
int index;
// If you want to start adding before the previous content, like new Tweets on twitter
index = 0;
// If you want to start adding after the previous content, like reading older tweets on twitter
index = self.json.count;
// Create the indexes with a loop
NSMutableArray *indexes = [NSMutableArray array];
for (int i = index; i < json.count; i++)
{
[indexes addObject:[NSIndexPath indexPathForItem:i inSection:0]];
}
// Perform the updates
[self.collectionView performBatchUpdates:^{
//Insert the new data to your current data
[self.json addObjectsFromArray:newJson];
//Inser the new cells
[self.collectionView insertItemsAtIndexPaths:indexes];
} completion:nil];
}