lxcid / LXReorderableCollectionViewFlowLayout

Extends `UICollectionViewFlowLayout` to support reordering of cells. Similar to long press and pan on books in iBook.
http://lxcid.com/
MIT License
1.86k stars 328 forks source link

Crash when reorder cell between section #102

Open adamwangxx opened 8 years ago

adamwangxx commented 8 years ago

So, I'm using the layout to create a collectionView, for some reason I create some sections and each section has one cell, and then when I reorder cells App will crash.

*\ Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 1. The number of items contained in an existing section after the update (1) must be equal to the number of items contained in that section before the update (1), plus or minus the number of items inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'

adamwangxx commented 8 years ago

Finally, I solve this issue by myself , it's quite easy. App will crash at

[self.collectionView performBatchUpdates:^{
        __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf.collectionView deleteItemsAtIndexPaths:@[ previousIndexPath ]];
            [strongSelf.collectionView insertItemsAtIndexPaths:@[ newIndexPath ]];
        }
    } completion:^(BOOL finished) {
        __strong typeof(self) strongSelf = weakSelf;
        if ([strongSelf.dataSource respondsToSelector:@selector(collectionView:itemAtIndexPath:didMoveToIndexPath:)]) {
            [strongSelf.dataSource collectionView:strongSelf.collectionView itemAtIndexPath:previousIndexPath didMoveToIndexPath:newIndexPath];
        }
    }];

in the FlowLayout.m file.

The code just delete previousIndexPath and insert newIndexPath at their section, for example previousIndexPath.section == 1, newIndexPath.section == 2, at this time we just remove a cell from section 1 and insert a cell into section2, but not add a cell into section 1 or delete cell belongs to section2, so we need add two new index to deal with the special case

    NSIndexPath *newIndexPath = [self.collectionView indexPathForItemAtPoint:self.currentView.center];
    NSIndexPath *tIndexPath = [NSIndexPath indexPathForRow:0 inSection:self.selectedItemIndexPath.section];
    NSIndexPath *previousIndexPath = self.selectedItemIndexPath;
    NSIndexPath *mIndexPath = [NSIndexPath indexPathForRow:0 inSection:newIndexPath.section];

That's all.

CYZZ commented 8 years ago

can you show me the demo ,give me a github URL to download it, THX.