从UICollectionView删除单元格而不从顶部重新加载

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

如何使用autolayout从UICollectionView中删除特定单元格?

UICollectionView将在删除后动画并自动重新排列单元格。

从集合视图中删除所选项目

[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方法中,在该特定单元格上添加按钮。

 - (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]; } } } 

在那个按钮动作中,

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

我认为它可以帮到你。

Interesting Posts