Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the only cell from UICollectionView with animation (deleteItemsAtIndexPaths)?

I'm getting an assertion while deleting a single UICollecitonViewCell from UICollectionView.

Precondition: I have a single cell (when I have two or more cells, the deletion works good).

Here is the code:

    NSIndexPath *ip = [_photosCollectionView indexPathForCell:cell];

    [_datasource removeItemAtIndex:ip.item];

    [_photosCollectionView deleteItemsAtIndexPaths:@[ip]]; // the assertion is raised

Here is the assertion text:

NSInternalInconsistencyException: attempt to delete item 0 from section 0 which only contains 0 items before the update

Quite strange issue, because it works for 2, 3 or more cells, but when I delete a single cell, it fails.

Any ideas what's wrong, how to work-around this issue?

like image 369
Vladimir Obrizan Avatar asked Jun 30 '14 11:06

Vladimir Obrizan


People also ask

How do I remove cells from collectionView?

Build and Run the project and select the Edit Button. Select a few cells and press the Trash button to remove the items.

What is a Uicollectionview?

An object that manages an ordered collection of data items and presents them using customizable layouts.


2 Answers

Thanks to similar questions and answers on SO, found a solution to use performBatchUpdates:

[_photosCollectionView performBatchUpdates:^ {
    [_datasource removeItemAtIndex:ip.item];
    [_photosCollectionView deleteItemsAtIndexPaths:@[ip]]; // no assertion now
} completion:nil];
like image 199
Vladimir Obrizan Avatar answered Oct 13 '22 06:10

Vladimir Obrizan


Same solution with Swift 4.1

    let indexPath = IndexPath(item: 0, section: 0)
    self.collectionView.performBatchUpdates({            
        self.collectionView.deleteItems(at:[indexPath])
    }, completion:nil)
like image 38
Tony Macaren Avatar answered Oct 13 '22 06:10

Tony Macaren