【发布时间】:2015-12-13 01:14:54
【问题描述】:
我正在使用以下代码删除 UICollectionView 中的项目:
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'
我调试了一下,好像delete代码通过调用来检查数据源中的项数:
collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int)
当您尝试删除最后一项时,由于您已从数据源中删除了一项,因此数据源中的项数将等于您尝试在 UI 集合中删除的索引。在这个断言示例中,我试图从最初有 5 个项目的数据源中删除索引为 4 的最后一个项目,当我从数据源中删除该项目时,项目数变为 4,这等于索引要从 UI 中删除的项目,因此删除代码会引发断言。
我不知道如何解决这个问题。正确的方法是先从数据源中删除项目,然后再从集合中删除。反过来做会给你其他断言。那么这样做的正确方法是什么?谢谢!
【问题讨论】:
标签: ios swift uicollectionview uicollectionviewcell