swift - 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 来获得正确的结果?
解决方案
我已经能够做到
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 调整。回到绘图板。
推荐阅读
- python - 在 python 中使用 urllib3 模块而不是请求
- java - 初学者 Java 将 arraylist 对象转换为输出字符串值?
- javascript - 我的过滤器系统在 html 中出现 JS 错误
- c# - 使用 C# 和 Unity 处理强大的清单项目,想知道这是否是从这个 json 文件中检索嵌套值的正确方法
- html - css bootstrap使行中的所有cols高度相同
- javascript - 尝试解决算法问题的曲折模式
- json - 如何从嵌套地图中获取值?
- javascript - 使用nodejs和mongodb的UnhandledPromiseRejection问题
- tensorflow - SHAP DeepExplainer:包含“nan”值的 shap_values
- button - 带中断的按钮计数器