Loading UICollectionViewCell one at a time

放肆的年华 提交于 2020-01-24 01:10:10

问题


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

    }

}

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/26805659/loading-uicollectionviewcell-one-at-a-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!