23

I have a UICollectionView and it works fine, but I want to add a few UICollectionViewCells items programmatically into the collection view.

So how can I achieve this?

To further clarify: when I say programmatically I mean inserting a cell during runtime, when an action is fired, not when the app is loaded (using the viewDidLoad method). I know when the model is updated and the call is made to UICollectionView in the insertItemsAtIndexPaths: method. It should create a new cells, but it's not doing that, it's throwing an error.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Muhammad Nasir
  • 1,796
  • 1
  • 14
  • 22
  • 1
    When you say "it's throwing an error" it's *very* helpful to say what that error is in your question. It's normally useful to see the actual code too, not just some text vaguely describing it. – Flexo Mar 24 '13 at 09:30
  • Ok ill post the code shortly. thanks Flexo – Muhammad Nasir Mar 24 '13 at 10:01

4 Answers4

26

...By referring to UICollectionView documentation

You can accomplish:

Inserting, Deleting, and Moving Sections and Items To insert, delete, or move a single section or item, follow these steps:

  1. Update the data in your data source object.
  2. Call the appropriate method of the collection view to insert or delete the section or item.

It is critical that you update your data source before notifying the collection view of any changes. The collection view methods assume that your data source contains the currently correct data. If it does not, the collection view might receive the wrong set of items from your data source or ask for items that are not there and crash your app. When you add, delete, or move a single item programmatically, the collection view’s methods automatically create animations to reflect the changes. If you want to animate multiple changes together, though, you must perform all insert, delete, or move calls inside a block and pass that block to the performBatchUpdates:completion: method. The batch update process then animates all of your changes at the same time and you can freely mix calls to insert, delete, or move items within the same block.

From your Question: you can for example register A gesture Recognizer, and Insert a NEW cell by doing the following:

in

// in .h 
@property (nonatomic, strong) NSMutableArray *data;

// in .m 
@synthesize data
// 

- (void)ViewDidLoad{
      //.... 

    myCollectonView.dataSource = self;
    myCollectionView.delegate = self; 
    data = [[NSMutableArray alloc] initWithObjects:@"0",@"1", @"2" @"3", @"4", 
                                                   @"5",@"6", @"7",  @"8", @"9",  
                                                   @"10", @"11", @"12", @"13",
                                                   @"14", @"15", nil];

    UISwipeGestureRecognizer *swipeDown = 
     [[UISwipeGestureRecognizer alloc] 
       initWithTarget:self action:@selector(addNewCell:)];
    swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
        [self.view addGestureRecognizer:swipeDown];
    //.. 
} 


-(void)addNewCell:(UISwipeGestureRecognizer *)downGesture {
    NSArray *newData = [[NSArray alloc] initWithObjects:@"otherData", nil];
    [self.myCollectionView performBatchUpdates:^{
        int resultsSize = [self.data count]; //data is the previous array of data
        [self.data addObjectsFromArray:newData];
        NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];

        for (int i = resultsSize; i < resultsSize + newData.count; i++) {
            [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i 
                                                              inSection:0]];
        }
        [self.myCollectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
    } completion:nil];

}
Silmaril
  • 4,241
  • 20
  • 22
abdimuna
  • 775
  • 9
  • 16
12

If you are inserting multiple items into UICollectionView, you can use performBatchUpdates:

[self.collectionView performBatchUpdates:^{
    // Insert the cut/copy items into data source as well as collection view
    for (id item in self.selectedItems) {
        // update your data source array
        [self.images insertObject:item atIndex:indexPath.row];
        
        [self.collectionView insertItemsAtIndexPaths:
          [NSArray arrayWithObject:indexPath]];          
    }
} completion:nil];
Vlad
  • 5,727
  • 3
  • 38
  • 59
Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
  • 1
    For inserting an item into collection view you need to specify an indexPath. Here iam performing insertion after cut/copy using menu operations so i know where to insert item. You can create one indexPath using `[NSIndexPath indexPathForItem:0 inSection:0]` and then insert item at that indexPath or it could be the selected item indexPath to insert in to the position of the selected item – Anil Varghese Mar 22 '13 at 14:36
  • [self.collectionView performBatchUpdates:^{ } completion:^(BOOL finished) { }]; Error may be because you didn't include the completion block – Vincent Joy Feb 03 '16 at 11:34
5

– insertItemsAtIndexPaths: does the job

Oleg
  • 2,984
  • 8
  • 43
  • 71
4

Here is how to insert an item in Swift 3 :

    let indexPath = IndexPath(row:index, section: 0) //at some index
    self.collectionView.insertItems(at: [indexPath])

You must first update your data.

Curnelious
  • 1
  • 16
  • 76
  • 150