Delete cell from UICollectionView without reloading from top
42,339
Solution 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
}
Solution 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.
Author by
New Jango Tester
Updated on July 09, 2022Comments
-
New Jango Tester almost 2 years
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?
-
Alok Chandra about 11 yearsdeletion time of the cell is fixed how to make animation slow or fast.
-
Anil Varghese about 11 yearsYou need to subclass the UICollectionViewFlowLayout. Particularly implement finalLayoutAttributForItemAtIndexPath. Check this
-
Tim Vermeulen over 8 years
[deleteButton bringSubviewToFront:collectionView];
seems to be an error.