【问题标题】:Is it possible to swap 2 cells in a UICollectionView that is using UICollectionViewFlowLayout?是否可以在使用 UICollectionViewFlowLayout 的 UICollectionView 中交换 2 个单元格?
【发布时间】:2012-12-14 21:37:30
【问题描述】:

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

1 2 3
4 5 6
7 8 9

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

1 2 3
4 5 9
7 8 6

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

中明确设置单元格的中心

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

但没有成功。

【问题讨论】:

    标签: objective-c uicollectionview


    【解决方案1】:

    经过多次头部撞击,我找到的解决方案是在performBatchUpdates:completion 内部使用moveItemAtIndexPath:toIndexPath。根据documentationperformBatchUpdates:completion

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

    所以,我基本上做的是

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

    【讨论】:

    • 您能否提供一些解释此特定问题的代码或教程。你是怎么解决这个问题的?
    • 你能在这个问题中提供任何关于这个问题的线索吗? stackoverflow.com/questions/25803120/…
    • 嗨 Zac24。我不知道此特定问题的任何示例代码。对不起。
    • 另外,您链接到的问题似乎已得到解答。你能详细说明一下吗?
    • 如果你愿意帮忙,那么我可以把我的代码/项目展示一下我到目前为止所做的尝试。
    【解决方案2】:

    您是否尝试过直接使用 moveItemAtIndexPath:toIndexPath: 重新排序项目?

    -确保您确实重新排序了基础模型集合,以便下次完全重新加载时更改保持不变。

    【讨论】:

    • 是的,我试过这样做。但由于我使用的是 UICollectionViewFlowLayout,因此动画无法正常工作,因为它会尝试更新源索引路径和目标索引路径之间的单元格。
    【解决方案3】:

    Swift 代码:

            self.collectionView.performBatchUpdates({
                self.collectionView.moveItem(at: selectedIndexPath, to: targetIndexPath)
                self.collectionView.moveItem(at: targetIndexPath, to: selectedIndexPath)
            }, completion: nil)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      相关资源
      最近更新 更多