UICollectionView:如何在加载视图之前和之后处理更新?
Posted
技术标签:
【中文标题】UICollectionView:如何在加载视图之前和之后处理更新?【英文标题】:UICollectionView: How to handle updates both before and after view is loaded? 【发布时间】:2014-02-15 10:58:45 【问题描述】:通过 KVO 接收这些更新时,我在更新集合视图时遇到问题。
例如对于删除,我执行以下操作:
dispatch_async(dispatch_get_main_queue(), ^
NSUInteger index = [self.albumObjects indexOfObject:oldObject];
NSIndexPath* indexPath = [NSIndexPath indexPathForItem:index inSection:0];
[self.dataSource removeObjectAtIndex:index];
[self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
上面给了我错误:
attempt to delete item 0 from section 0 which only contains 0 items before the update
好的...所以让我们之后从数据源中删除然后返回以下错误:
dispatch_async(dispatch_get_main_queue(), ^
NSUInteger index = [self.albumObjects indexOfObject:oldObject];
NSIndexPath* indexPath = [NSIndexPath indexPathForItem:index inSection:0];
[self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
[self.dataSource removeObjectAtIndex:index];
但是我现在收到以下错误:
Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (1) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).
看来我赢不了?我在这里做错了什么?
【问题讨论】:
【参考方案1】:dispatch_async() 似乎会导致异常:当您修改数据源(将更新程序块添加到主队列的末尾)时,当您尝试更新 collectionView 时,该项目已被删除。
您使用什么数据源?是手动管理的吗?还是 viewController 正在观察数据源?
【讨论】:
以上是关于UICollectionView:如何在加载视图之前和之后处理更新?的主要内容,如果未能解决你的问题,请参考以下文章
如何从JSON加载特定数据并显示UICollectionView?
如何仅重新加载 UICollectionView 的可见部分?
如何告诉 UICollectionView 预加载更大范围的单元格?
将附加视图插入从 Xib 加载的 UICollectionView