一次加载一个UICollectionViewCell

按照这篇文章http://aplus.rs/2014/how-to-animate-in-uicollectionview-items/我试图一次加载一个UICollectionViewCellanimation单元格出现时。 但是,当我调用代码循环cellCount ++,它会产生这样的错误:

由于未捕获的exception“NSInternalInconsistencyException”而终止应用程序,原因是:“无效的更新:部分0中的项目数目无效。更新(1)之后现有部分中包含的项目数量必须等于(1),加上或减去从该部分插入或删除的项目数(插入1个,删除0个),加上或减去移入或移出该部分的项目数(0移入,0移入出)。”

我不能为我的生活弄清楚。

这是我的代码:

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

您可以使用计时器执行此操作,该计时器的操作方法将数据源数组中的对象添加到可用于填充集合视图的可变数组中。

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

只有在数据源与您添加单元格的操作紧密协调的情况下,这种事情才有效。

因此, 调用insertItemsAtIndexPaths 之前 ,请确保您的数据源numberOfItemsInSection为0部分回答您的模型计数。 您的模型计数需要完全匹配cellCount ,并且您的cellForItemAtIndexPath需要准备访问项目0..cellCount-1