是否可以在使用UICollectionViewFlowLayout的UICollectionView中交换2个单元格?

J.C*_*.C. 13 objective-c uicollectionview

假设我使用UICollectionViewFlowLayout和以下格式的UICollectionView:

1 2 3
4 5 6
7 8 9
Run Code Online (Sandbox Code Playgroud)

我触摸单元格9并将其拖到单元格6上,将单元格9移动到单元格6所在的位置,将单元格6移动到单元格9所在的位置:

1 2 3
4 5 9
7 8 6
Run Code Online (Sandbox Code Playgroud)

是否有任何方法可以轻松地移动单元格6并将其设置为单元格9的位置以及将单元格9移动到单元格6所在的位置?或者我是否必须继承UICollectionViewLayout?如果我必须继承UICollectionViewLayout,那怎么办呢?我已经尝试明确设置细胞的中心

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

但没有成功.

J.C*_*.C. 22

经过多次敲击,我找到的解决方案就是在moveItemAtIndexPath:toIndexPath里面使用performBatchUpdates:completion.根据该文件performBatchUpdates:completion:

如果要在一个动画操作中插入,删除,重新加载或移动集合视图周围的单元格,而不是在几个单独的动画中,则可以使用此方法.使用updates参数中传递的阻止来指定要执行的所有操作.

所以,我基本上做的是

[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];
}];
Run Code Online (Sandbox Code Playgroud)