-->

Delete cell from UICollectionView without reloadin

2019-01-17 02:00发布

问题:

I am using a CollectionView in my ios app. Each collection cell contains a delete button. By clicking the button the cell should be deleted. After deletion, that space will be filled with below cell (I don't wish to reload the CollectionView and start from top again)

How do I delete a particular cell from UICollectionView with autolayout?

回答1:

UICollectionView will animate and automatically rearrange the cells after deletion.

Delete selected items from collection view

[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

}


回答2:

No delegate methods provided to UICollectionViewController as like UITableviewController. We can do it manually by adding a long gesture recognizer to UICollectionView.

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

In longGesture method add button on that particular cell.

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

In that button action,

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

I think it can help you.