Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add more UICollectionViewCell to an existing UICollectionView

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?

like image 388
Anderson Bressane Avatar asked Nov 01 '12 19:11

Anderson Bressane


2 Answers

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.

like image 193
chris Avatar answered Sep 27 '22 21:09

chris


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];
 }
like image 20
Anderson Bressane Avatar answered Sep 27 '22 21:09

Anderson Bressane