从UICollectionView中删除单元格

我在我的iPhone应用程序中使用CollectionView。 每个收集单元都包含一个删除button。 通过点击button,单元格应该被删除。 删除后,该空间将填充下面的单元格(我不希望重新加载CollectionView,并从顶部再次开始)

如何使用自动布局从UICollectionview中删除特定的单元格?

UICollectionView将animation和删除后自动重新排列单元格。

从集合视图中删除选定的项目

[self.collectionView performBatchUpdates:^{ NSArray *selectedItemsIndexPaths = [self.collectionView indexPathsForSelectedItems]; // Delete the items from the data source. [self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths]; // Now delete the items from the collection view. [self.collectionView deleteItemsAtIndexPaths:selectedItemsIndexPaths]; } completion:nil]; // This method is for deleting the selected images from the data source array -(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray *)itemPaths { NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet]; for (NSIndexPath *itemPath in itemPaths) { [indexSet addIndex:itemPath.row]; } [self.images removeObjectsAtIndexes:indexSet]; // self.images is my data source } 

没有像UITableviewController一样提供给UICollectionViewController的委托方法。 我们可以通过向UICollectionView添加一个长手势识别器手动完成。

  UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(activateDeletionMode:)]; longPress.delegate = self; [collectionView addGestureRecognizer:longPress]; 

在longGesture方法中添加特定单元格的button。

 - (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr { if (gr.state == UIGestureRecognizerStateBegan) { if (!isDeleteActive) { NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:[gr locationInView:collectionView]]; UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; deletedIndexpath = indexPath.row; [cell addSubview:deleteButton]; [deleteButton bringSubviewToFront:collectionView]; } } } 

在那个button动作中,

 - (void)delete:(UIButton *)sender { [self.arrPhotos removeObjectAtIndex:deletedIndexpath]; [deleteButton removeFromSuperview]; [collectionView reloadData]; } 

我认为它可以帮助你。