更UICollectionViewCell添加到现有UICollectionView(Add mor

2019-07-03 12:11发布

我想一些单元添加到现有的UICollectionView ,这已经是充满了某种细胞。

我试图用的CollectionView reloadData但似乎重新加载整个的CollectionView,我只是想添加更多的细胞。

有谁能够帮我?

Answer 1:

UICollectionView类有方法来添加/删除项目。 例如,插入一些项目index (第0 ),相应地修改你的模型,然后做:

int indexPath = [NSIndexPath indexPathForItem:index];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath inSection:0];
[collectionView insertItemsAtIndexPaths:indexPaths];

该视图将做休息。



Answer 2:

插入新的细胞对UICollectionView而不必重新加载其所有细胞的最简单的方法是通过使用performBatchUpdates,它可以很容易地通过下面的步骤来完成。

// Lets assume you have some data coming from a NSURLConnection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *erro)
{
      // Parse the data to Json
      NSMutableArray *newJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

      // Variable used to say at which position you want to add the cells
      int index;

      // If you want to start adding before the previous content, like new Tweets on twitter
      index = 0;

      // If you want to start adding after the previous content, like reading older tweets on twitter
      index = self.json.count;

      // Create the indexes with a loop
      NSMutableArray *indexes = [NSMutableArray array];

      for (int i = index; i < json.count; i++)
      {
            [indexes addObject:[NSIndexPath indexPathForItem:i inSection:0]];
      }

      // Perform the updates
      [self.collectionView performBatchUpdates:^{

           //Insert the new data to your current data
           [self.json addObjectsFromArray:newJson];

           //Inser the new cells
           [self.collectionView insertItemsAtIndexPaths:indexes];

      } completion:nil];
 }


文章来源: Add more UICollectionViewCell to an existing UICollectionView