从UICollectionView中删除最后一项时,断言失败

时间:2015-12-13 01:14:55

标签: 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!.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中删除的项目的索引,因此删除代码会引发断言 我不知道怎么解决这个问题。正确的方法是首先从数据源中删除项目,然后从集合中删除。反过来做它会给你其他的断言。那么这样做的正确方法是什么?谢谢!

3 个答案:

答案 0 :(得分:2)

我解决了我的问题。这不是我删除项目的方式。上述机制是正确的。代码中的其他地方我在删除后调用reloadItemsAtIndexPaths。我仍然不知道为什么会导致断言,但删除reloadItemsAtIndexPaths解决了这个问题而不会影响我的程序。看来我一开始并不需要这样做。

答案 1 :(得分:1)

我遇到了同样的问题并找到了解决方案:

在处理删除的代码中,您需要检查是否要删除该部分中的最后一项。如果要删除最后一项,则还需要重新加载该部分。像这样:

__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];

答案 2 :(得分:0)

尝试从更新块内的列表中删除该项目。

相关问题