Ios 从UICollectionView中删除最后一项时获取断言失败
我正在使用以下代码删除UICollectionView中的项目:Ios 从UICollectionView中删除最后一项时获取断言失败,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我正在使用以下代码删除UICollectionView中的项目: func DeleteItem(indexPath: NSIndexPath) { // remove from the data source myList.removeObjectAtIndex(indexPath.item) // remove the item from the collection view self.collectionView!.performBatchUpdat
func DeleteItem(indexPath: NSIndexPath) {
// remove from the data source
myList.removeObjectAtIndex(indexPath.item)
// remove the item from the collection view
self.collectionView!.performBatchUpdates({
self.collectionView?.deleteItemsAtIndexPaths([indexPath])
}, completion: nil)
}
这很好,除非我想删除列表中的最后一项,即使列表不是空的。我得到以下断言失败:
'NSInternalInconsistencyException', reason: 'attempt to delete item 4 from section 0 which only contains 4 items before the update'
我调试了它,似乎删除代码通过调用以下命令来检查数据源中的项数:
collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int)
当您尝试删除最后一个项目时,由于您已从数据源中删除了一个项目,因此数据源中的项目数将等于您尝试在UI集合中删除的索引数。在这个断言示例中,我试图从最初有5个项目的数据源中删除索引为4的最后一个项目,当我从数据源中删除该项目时,项目数变为4,这等于要从UI中删除的项目的索引,因此删除代码引发断言。我不知道如何避开这件事。正确的方法是先从数据源中删除项,然后再从集合中删除项。反过来做,你会得到其他的断言。那么,正确的方法是什么呢?谢谢 尝试从更新块内的列表中删除该项 我解决了我的问题。这与我删除一个项目的方式无关。上述机制是正确的。在代码的其他地方,我在删除之后调用了ReloadItemSatinDexpath。我仍然不知道为什么会导致断言,但是删除ReloadItemSatinDexpath在不影响我的程序的情况下解决了这个问题。似乎我一开始就不需要这样做。我遇到了同样的问题并找到了解决方案: 在处理删除的代码中,您需要检查是否正在删除节中的最后一项。如果要删除最后一项,则还需要重新加载该节。大概是这样的:
__weak typeof(self)weakSelf = self;
[items removeObjectAtIndex:index];
[self.collectionView performBatchUpdates:^{
[weakSelf.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:sectionIndex]]];
if (items.count == 0) {
[weakSelf.collectionView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex]];
}
} completion:nil];
我做到了,我得到了我为你发布的断言。