25

我需要知道何时重新加载 UICollectionView 以在之后配置单元格(因为我不是单元格的数据源 - 否则已经完成了......)

我试过代码,比如

[self.collectionView reloadData];
[self configure cells]; // BOOM! cells are nil

我也尝试过使用

[self.collectionView performBatchUpdates:^{
  [self.collectionView reloadData];
    } completion:^(BOOL finished) {
        // notify that completed and do the configuration now
  }];

但是当我重新加载数据时,我会崩溃。

如何将数据重新加载到集合中,并且仅在完成重新加载后 - 执行特定的完成处理程序

4

3 回答 3

99

这是由于在 layoutSubviews 期间添加的单元格不是在 reloadData 处。由于 layoutSubviews 在 reloadData 之后的下一个运行循环传递期间执行,因此您的单元格为空。尝试这样做:

[self.collectionView reloadData];
[self.collectionView layoutIfNeeded];
[self configure cells]; 

我有类似的问题并以这种方式解决。

于 2013-08-21T11:25:55.400 回答
7

如果你想在你的 collectionView 完成它的 reloadData() 方法后执行一些代码,那么试试这个(Swift):

    self.collectionView.reloadData()
    self.collectionView.layoutIfNeeded()
    dispatch_async(dispatch_get_main_queue()) { () -> Void in
        // Put the code you want to execute when reloadData is complete in here
    }

这样做的原因是因为调度块中的代码被放到了行的后面(也称为队列)。这意味着它在打开主线程之前排队等待所有主线程操作完成,包括 reloadData() 的方法。

于 2016-02-01T21:04:19.280 回答
5

不支持在reloadData. 所有动画都必须使用方法执行,例如

[collectionView deleteItemsAtIndexPaths:indexesToDelete];
[collectionView insertSections:sectionsToInsert];
[collectionView reloadItemsAtIndexPaths:fooPaths];

块内performBatchUpdates:。该reloadData方法只能用于粗略刷新,当所有项目都被移除并重新布局而没有动画时。

于 2015-06-04T12:30:13.643 回答