是否可以在使用 UICollectionViewFlowLayout 的 UICollectionView 中交换 2 个单元格? [英] Is it possible to swap 2 cells in a UICollectionView that is using UICollectionViewFlowLayout?

查看:51
本文介绍了是否可以在使用 UICollectionViewFlowLayout 的 UICollectionView 中交换 2 个单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 UICollectionView 使用 UICollectionViewFlowLayout 和以下格式:

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

1 2 3
4 5 6
7 8 9

我触摸单元格 9 并将其拖到单元格 6 上,将单元格 9 移动到单元格 6 所在的位置,将单元格 6 移动到单元格 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

有什么方法可以轻松地将单元格 6 移动和动画到单元格 9 所在的位置以及将单元格 9 移动和动画到单元格 6 所在的位置?或者我必须继承 UICollectionViewLayout 吗?如果我必须继承 UICollectionViewLayout,这将如何完成?我已经尝试在

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

但没有成功.

推荐答案

经过一番折腾,我找到的解决方案是在 performBatchUpdates:completion 内使用 moveItemAtIndexPath:toIndexPath>.根据 文档 performBatchUpdates:completion:

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

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

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.

所以,我基本上做的是

[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];
}];

这篇关于是否可以在使用 UICollectionViewFlowLayout 的 UICollectionView 中交换 2 个单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆