21

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

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

4

2 回答 2

37

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

}
于 2013-04-24T11:02:27.830 回答
7

没有像 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];
}

我认为它可以帮助你。

于 2013-04-24T11:00:13.320 回答