【问题标题】:Getting assertion failure when deleting the last item from a UICollectionView从 UICollectionView 中删除最后一项时出现断言失败
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 我做了,我得到了我为你发布的断言。
        猜你喜欢
        • 1970-01-01
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-17
        • 2017-01-13
        相关资源
        最近更新 更多