如何以编程方式在UICollectionVIew中插入单元格?

我有一个UICollectionView ,它工作正常,但我想以编程方式添加一些UICollectionViewCells项目到集合视图。

那么我怎么能做到这一点呢?

为了进一步阐明:当我以编程的方式说我的意思是插入一个单元格在运行时,当一个动作被激发,而不是当应用程序被加载(使用viewDidLoad方法)。 我知道模型何时被更新,并且在insertItemsAtIndexPaths:方法中调用了UICollectionView 。 它应该创build一个新的单元格,但不是这样做的,这是抛出一个错误。

…通过参考UICollectionView文档

你可以完成:

插入,删除和移动部分和项目要插入,删除或移动单个部分或项目,请执行以下步骤:

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

在通知任何更改的集合视图之前,更新数据源至关重要。 集合视图方法假定您的数据源包含当前正确的数据。 如果没有,收集视图可能会从您的数据源收到错误的项目集合,或者询问那些不存在的项目,并使您的应用程序崩溃。 以编程方式添加,删除或移动单个项目时,集合视图的方法会自动创buildanimation以反映更改。 但是,如果要一起animation多个更改,则必须在块内执行所有插入,删除或移动调用,并将该块传递给performBatchUpdates:completion:方法。 批量更新过程然后在同一时间animation化所有更改,并且可以自由混合调用以在同一个块内插入,删除或移动项目。

从你的问题:你可以例如注册一个手势识别器,并通过执行以下插入一个新的单元格:

 // in .h @property (nonatomic, strong) NSMutableArray *data; // in .m @synthesize data // - (void)ViewDidLoad{ //.... myCollectonView.dataSource = self; myCollectionView.delegate = self; data = [[NSMutableArray alloc] initWithObjects:@"0",@"1", @"2" @"3", @"4", @"5",@"6", @"7", @"8", @"9", @"10", @"11", @"12", @"13", @"14", @"15", nil]; UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(addNewCell:)]; swipeDown.direction = UISwipeGestureRecognizerDirectionDown; [self.view addGestureRecognizer:swipeDown]; //.. } -(void)addNewCell:(UISwipeGestureRecognizer *)downGesture { NSArray *newData = [[NSArray alloc] initWithObjects:@"otherData", nil]; [self.myCollectionView performBatchUpdates:^{ int resultsSize = [self.data count]; //data is the previous array of data [self.data addObjectsFromArray:newData]; NSMutableArray *arrayWithIndexPaths = [NSMutableArray array]; for (int i = resultsSize; i < resultsSize + newData.count; i++) { [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]]; } [self.myCollectionView insertItemsAtIndexPaths:arrayWithIndexPaths]; } completion:nil]; } 

如果你插入多个itemsUICollectionView ,你可以使用performBatchUpdates:

 [self.collectionView performBatchUpdates:^{ // Insert the cut/copy items into data source as well as collection view for (id item in self.selectedItems) { // update your data source array [self.images insertObject:item atIndex:indexPath.row]; [self.collectionView insertItemsAtIndexPaths: [NSArray arrayWithObject:indexPath]]; } } 

– insertItemsAtIndexPaths:做这个工作

这里是如何在Swift 3中插入一个项目:

  let indexPath = IndexPath(row:index, section: 0) //at some index self.collectionView.insertItems(at: [indexPath]) 

您必须先更新您的数据。