10

我正在尝试将更多单元格添加到现有UICollectionView的已填充一些单元格的现有单元格中。

我尝试使用 CollectionView reloadData,但它似乎重新加载了整个 collectionView,我只想添加更多单元格。

有谁能够帮助我?

4

2 回答 2

6

该类UICollectionView具有添加/删除项目的方法。例如,要在某个index(在 section 中0)插入一个项目,相应地修改您的模型,然后执行:

int indexPath = [NSIndexPath indexPathForItem:index];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath inSection:0];
[collectionView insertItemsAtIndexPaths:indexPaths];

视图将完成其余的工作。

于 2012-11-01T20:49:42.020 回答
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];
 }
于 2014-08-28T21:11:02.287 回答