如何从动画中删除UICollectionView中唯一的单元格(deleteItemsAtIndexPaths)?

Vla*_*zan 11 objective-c ios uicollectionview uicollectionviewcell

在删除一个我得到断言UICollecitonViewCellUICollectionView.

前提条件:我有一个单元格(当我有两个或更多单元格时,删除效果很好).

这是代码:

    NSIndexPath *ip = [_photosCollectionView indexPathForCell:cell];

    [_datasource removeItemAtIndex:ip.item];

    [_photosCollectionView deleteItemsAtIndexPaths:@[ip]]; // the assertion is raised
Run Code Online (Sandbox Code Playgroud)

这是断言文本:

NSInternalInconsistencyException: attempt to delete item 0 from section 0 which only contains 0 items before the update
Run Code Online (Sandbox Code Playgroud)

非常奇怪的问题,因为它适用于2,3或更多单元格,但是当我删除单个单元格时,它会失败.

任何想法有什么不对,如何解决这个问题?

Vla*_*zan 14

感谢SO上的类似问题和答案,找到了一个使用的解决方案performBatchUpdates:

[_photosCollectionView performBatchUpdates:^ {
    [_datasource removeItemAtIndex:ip.item];
    [_photosCollectionView deleteItemsAtIndexPaths:@[ip]]; // no assertion now
} completion:nil];
Run Code Online (Sandbox Code Playgroud)


小智 5

与Swift 4.1相同的解决方案

    let indexPath = IndexPath(item: 0, section: 0)
    self.collectionView.performBatchUpdates({            
        self.collectionView.deleteItems(at:[indexPath])
    }, completion:nil)
Run Code Online (Sandbox Code Playgroud)

  • 回答问题时,请不要仅仅发布代码。重要的是要解释它为什么起作用和/或它如何解决OP的问题:) (2认同)