spogebob92
spogebob92

Reputation: 1484

Loading UICollectionViewCell one at a time

As per this article http://aplus.rs/2014/how-to-animate-in-uicollectionview-items/ I am trying to load a UICollectionViewCell one at a time to animate the cell when it appears. However, when I call the code the loops the cellCount++, it produces this error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (1) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'

And I cannot for the life of me figure it out.

Here is my code:

-(void)addCells{

    for (self.cellCount=0; self.cellCount<50; self.cellCount++) {

        [self.collectionView performBatchUpdates:^{
            [self.collectionView insertItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:self.cellCount inSection:0]]];
        } completion:nil];

    }

}

Upvotes: 0

Views: 915

Answers (2)

rdelmar
rdelmar

Reputation: 104082

You can do this using a timer, whose action method adds objects from your data source array to a mutable array that you use to populate your collection view.

-(void)viewDidLoad {
    [super viewDidLoad];
    self.mutableArray = [NSMutableArray new];
    self.data = @[@"one", @"one", @"one", @"one", @"one", @"one"];
    [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(addCells:) userInfo:nil repeats:YES];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.mutableArray.count;
}


-(void)addCells:(NSTimer *) timer {
    static int counter = 0;
    [self.mutableArray addObject:self.data[counter]];
    counter ++;
    [self.collectionview insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:self.mutableArray.count -1 inSection:0]]];
    if (self.mutableArray.count == self.data.count) {
        [timer invalidate];
    }
}

Upvotes: 3

danh
danh

Reputation: 62676

This sort of thing only works when the datasource is tightly coordinated with the actions you take to add cells.

So before you call insertItemsAtIndexPaths, make sure that your datasource numberOfItemsInSection for section 0 answers your model count. Your model count needs to match cellCount exactly, and your cellForItemAtIndexPath needs to be prepared to access items 0..cellCount-1.

Upvotes: 1

Related Questions