Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to swap 2 cells in a UICollectionView that is using UICollectionViewFlowLayout?

Say I have a UICollectionView using a UICollectionViewFlowLayout and the following format:

1 2 3
4 5 6
7 8 9

I touch cell 9 and drag it over cell 6, moving cell 9 to where cell 6 is and cell 6 to where cell 9 was:

1 2 3
4 5 9
7 8 6

Is there any way to easily move and animate cell 6 to where cell 9 is as well as move and animate cell 9 to where cell 6 is? Or do I have to subclass UICollectionViewLayout? If I have to subclass UICollectionViewLayout, how would this be done? I've tried explicitly setting the centers of the cells in

-(UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

but to no success.

like image 965
J.C. Avatar asked Dec 14 '12 21:12

J.C.


1 Answers

After much head banging, the solution I found is to use moveItemAtIndexPath:toIndexPath inside of performBatchUpdates:completion. According to the documentation for performBatchUpdates:completion:

You can use this method in cases where you want to insert, delete, reload or move cells around the collection view in one single animated operation, as opposed to in several separate animations. Use the blocked passed in the updates parameter to specify all of the operations you want to perform.

So, what I essentially did was

[self performBatchUpdates:^{
    [self moveItemAtIndexPath:fromIp toIndexPath:toIp];
    [self moveItemAtIndexPath:toIp toIndexPath:fromIp];
} completion:^(BOOL finished) {
    // update data source here
    // e.g [dataSource exchangeObjectAtIndex:fromIp.row withObjectAtIndex:toIp.row];
}];
like image 115
J.C. Avatar answered Nov 16 '22 02:11

J.C.