插入新的单元格到UICollectionView

我试图添加一个新的单元格到我的集合视图,只有当它有多个项目已经在它。 我没有收集意见的工作太多,在文档和本网站的研究还没有帮助解决这个问题呢。 所以,在我的cellForItemAtIndexPath方法,我做了检查,看看它是否填充。 如果没有,我添加单元格,如下所示:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { if (self.myArray.count != 0) { return self.myArray.count + 1; } else { return self.myArray.count; } } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { MyNormalCollectionViewCellS *cells = (MyNormalCollectionViewCells *) [collectionView dequeueReusableCellWithReuseIdentifier:@"MyNormalCollectionViewCells” forIndexPath:indexPath]; cell.clipsToBounds = NO; DataClass *data = [self.myArray objectAtIndex:indexPath.row]; [cells configureMyNormalCellsWith:data]; if (0 < self.myArray.count) { UICollectionViewCell *deleteCell = [UICollectionViewCell new]; deleteCell.backgroundColor = [UIColor yellowColor]; NSArray *newData = [[NSArray alloc] initWithObjects:deleteCell, nil]; [self.myArray addObjectsFromArray:newData]; NSMutableArray *arrayWithIndexPaths = [NSMutableArray array]; [self.myCollectionView insertItemsAtIndexPaths:arrayWithIndexPaths]; return deleteCell; } return cell; } 

出于某种原因,我有一个断言,说:

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

当然,这个数字通常是不一样的,但是总是对这个额外的单元格感到愤怒。 一切都很好,直到我尝试添加它。现在,不熟悉收集意见,并在浏览本网站上的相关问题后,我决定是时候问专业人士。

有谁知道我应该改变这个代码,以完成我想要做的?

不要在collectionView:cellForItemAtIndexPath:修改数据源。 返回不同数量的项目在- collectionView:numberOfItemsInSection:相反:

 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { if (self.dataArray.count > 0) { return self.dataArray.count + 1; } else { return 0; } } 

collectionView:cellForItemAtIndexPath:你应该返回你的“正常”单元格为“正常”的项目和“额外”单元格的多余,这取决于indexPath.row的值。 例如:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row < self.dataArray.count) { // if indexPath.row is within data array bounds // dequeue, setup and return "normal" cell } else { // this is your "+1" cell // dequeue, setup and return "extra" cell } }