UICollectionView使用performBatchUpdates执行更新

时间:2012-09-29 21:31:02

标签: objective-c ios xcode ipad uicollectionview

我有一个UICollectionView,我试图动态/动画插入项目。所以我有一些函数可以异步下载图像,并希望批量插入项目。

获得数据后,我想执行以下操作:

[self.collectionView performBatchUpdates:^{
    for (UIImage *image in images) {
        [self.collectionView insertItemsAtIndexPaths:****]
    }
} completion:nil];

现在代替***,我应该传递一个NSIndexPaths数组,它应该指向要插入的新项目的位置。我提供位置后非常困惑,如何提供应该在该位置显示的实际图像?

谢谢


更新

resultsSize的数据添加新数据之前,

self.results包含数据源数组newImages的大小。

[self.collectionView performBatchUpdates:^{

    int resultsSize = [self.results count];
    [self.results addObjectsFromArray:newImages];
    NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];

    for (int i = resultsSize; i < resultsSize + newImages.count; i++)
          [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];

          [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];

} completion:nil];

2 个答案:

答案 0 :(得分:29)

请参阅“Inserting, Deleting, and Moving Sections and Items”中的Collection View Programming Guide for iOS

  

要插入,删除或移动单个部分或项目,您必须遵循   这些步骤:

     
      
  1. 更新数据源对象中的数据。
  2.   
  3. 调用集合视图的相应方法以插入或删除节或项目。
  4.         

    在通知之前更新数据源至关重要   集合视图的任何变化。集合视图方法假设   您的数据源包含当前正确的数据。如果是的话   不是,集合视图可能会收到错误的项目集   您的数据源或询问不存在的项目并使您崩溃   应用

因此,在您的情况下,您必须首先将图像添加到集合视图数据源,然后调用insertItemsAtIndexPaths。然后,集合视图将要求数据源委托函数提供插入项的视图。

答案 1 :(得分:6)

我在从索引中删除项目时遇到了类似的问题,这是我认为在使用performBatchUpdates:方法时我们需要做的事情。

1#首先调用deleteItemAtIndexPath从集合视图中删除该项目。

2#从数组中删除元素。

3#通过重新加载数据来更新集合视图。

[self.collectionView performBatchUpdates:^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
            [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
            [self.addNewDocumentArray removeObjectAtIndex:sender.tag];
        } completion:^(BOOL finished) {
            [self.collectionView reloadData];
        }];

这有助于我删除所有崩溃和断言失败。