【发布时间】:2016-02-15 07:01:25
【问题描述】:
我想从 UICollectionView 中删除一个单元格。在删除单元格时,我得到了
*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 0 节中的项目数无效。更新后现有节中包含的项目数 (5) 必须等于更新前该节中包含的项目数 (5),加上或减去从该节插入或删除的项目数(0 插入,1 个删除),加上或减去移入或移出该节的项目数( 0 搬入,0 搬出)。错误。
这是我的代码:
[self.imgArray removeObjectAtIndex:indexForDelete];
[self.collectionView performBatchUpdates:^{
NSIndexPath *indexPath =[NSIndexPath indexPathForItem:indexForDelete inSection:0];
[self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
} completion:^(BOOL finished) {
}];
当我的数组计数不是 5 时,我正在附加一个虚拟单元 这是 numberOfItemsInSection 中 numberOfItems 的代码
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
if(self.imgArray.count == 5)
{
return self.imgArray.count ;
}
else
{
return self.imgArray.count + 1;
}
}
我在 Google 和 Stackoverflow 上找到了许多解决方案,但没有找到完全适合我的解决方案。
【问题讨论】:
-
单次删除不需要
performBatchUpdates。摆脱它,只保留块内的两行。 -
你能展示你的
numberOfItemsInSection方法吗? -
查看我更新的问题。 @Paulw11
-
所以该代码解释了您的问题。数组中有 5 项,所以
numberOfItemsInSection返回 5,然后删除 1,所以现在有 4,但numberOfItemsInSection仍然返回 5。这正是您的异常所说的。为什么会有那个 if 语句? -
@Paulw11 :你是对的。正好 5 会引发问题。
标签: ios objective-c cocoa-touch uicollectionview