将更多UICollectionViewCell添加到现有的UICollectionView

And*_*ane 10 xcode ios6 uicollectionview uicollectionviewcell

我正在尝试向现有的单元格中添加更多单元UICollectionView格.

我试图使用CollectionView,reloadData但它似乎重新加载整个collectionView,我只是想添加更多的单元格.

有谁能够帮我?

chr*_*ris 6

UICollectionView类有方法来添加/删除项目.例如,要在某些index(在部分中0)插入项目,请相应地修改模型,然后执行以下操作:

int indexPath = [NSIndexPath indexPathForItem:index];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath inSection:0];
[collectionView insertItemsAtIndexPaths:indexPaths];
Run Code Online (Sandbox Code Playgroud)

该视图将完成剩下的工作.


And*_*ane 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];
 }
Run Code Online (Sandbox Code Playgroud)