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

后端 未结 3 1756
我寻月下人不归
我寻月下人不归 2021-02-05 15:54

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 ce

相关标签:
3条回答
  • 2021-02-05 16:00

    Have you tried re-ordering the items directly using moveItemAtIndexPath:toIndexPath: ?

    -make sure you actually re-order the underlying model collection so that the changes stick when you do a full reload next time.

    0 讨论(0)
  • 2021-02-05 16:03

    Swift code:

            self.collectionView.performBatchUpdates({
                self.collectionView.moveItem(at: selectedIndexPath, to: targetIndexPath)
                self.collectionView.moveItem(at: targetIndexPath, to: selectedIndexPath)
            }, completion: nil)
    
    0 讨论(0)
  • 2021-02-05 16:20

    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];
    }];
    
    0 讨论(0)
提交回复
热议问题