首页 > 解决方案 > Swift indexPath 数组计算

问题描述

我正在尝试解决如何使用 .map 为 peformBatchUpdates 函数修改 collectionView 中的插入 indexPaths

假设我在 collectionView 中有项目 1 2 3 4 5 6 7 和要删除的 indexPaths 数组

▿ 2 elements
  ▿ 0 : 2 elements
    - 0 : 0
    - 1 : 0
  ▿ 1 : 2 elements
    - 0 : 0
    - 1 : 1

和一个用于插入的 indexPaths 数组

▿ 2 elements
  ▿ 0 : 2 elements
    - 0 : 0
    - 1 : 3
  ▿ 1 : 2 elements
    - 0 : 0
    - 1 : 4

我相信 performBatchUpdates 操作的插入 indexPaths 需要在执行删除后计算,因此看到删除是 collectionView 项目中的前 2 个项目,insertingIndexPaths 的 indexPath.item 需要减少 2 才能插入正确的位置,即我希望最终的 insertIndexPaths 是......

▿ 2 elements
  ▿ 0 : 2 elements
    - 0 : 0
    - 1 : 1
  ▿ 1 : 2 elements
    - 0 : 0
    - 1 : 2

本质上,我认为我需要检查 insertIndexPath 数组中的每个 indexPath.item,查看该 insertIndexPath 前面有多少个deletionIndexPaths,然后将insertingIndexPath.item 递减该数字。

我如何在这些插入索引路径上使用 .map 来获得正确的结果?

标签: swiftfunctional-programminguicollectionviewnsindexpathperformbatchupdates

解决方案


我已经能够做到

            let adjustedPageDestinationIndexPaths = pageDestinationIndexPaths.map { ( indexPath ) -> IndexPath in
                return IndexPath(item: indexPath.item - pageSourceIndexPaths.filter { $0.item < indexPath.item }.count , section: 0)
            }

这为下面的示例提供了正确调整的 indexPaths,仅将 2 个项目从位置 0 和 1 移动到位置 3 和 4,但现在意识到在 collectionView 中一次移动的项目数量越多,我需要的项目数量就越多track 计算每个循环上的源 indexPath 和目标 indexPath 调整。回到绘图板。


推荐阅读