Add more UICollectionViewCell to an existing UICol

2019-02-16 21:10发布

问题:

I'm trying to add some more cells to an existing UICollectionView, which is already filled with some cells.

I tried to use the CollectionView reloadData but it seems to reload the entire collectionView and I just wanted to add more cells.

Can anybody help me?

回答1:

The UICollectionView class has methods to add/remove items. E.g., to insert an item at some index (in section 0), modify your model accordingly and then do:

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

The view will do the rest.



回答2:

The easiest way to insert new cells to the UICollectionView without having to reload all its cell is by using the performBatchUpdates, which can be done easily by following the steps below.

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