You need to enable JavaScript to run this app. SwiftUI中如何将onMove修饰符与多维数组结合使用
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何将onMove修饰符与多维数组结合使用

SwiftUI onMove修饰符适配多维数组的实现方案

问题核心

当前代码中onMove修饰符绑定的是遍历多维数组外层维度的ForEach,所以默认只能实现外层子数组的整体移动,无法直接操作内层的单个元素。根据实际需求可选择以下两种实现方案:


方案1:实现外层子数组整体移动

适合需要整组移动元素的场景,调整后可直接运行:

@State var multiArray = [["String_1_1", "String_1_2"],["String_2_1", "String_2_2"]] // 多元素可直观看出分组移动效果
@State var edit: Bool = false

var body: some View {
    NavigationStack{ // iOS16+已废弃NavigationView,推荐使用NavigationStack
        List {
            Section{
                Button(edit ? "完成" : "编辑") {
                    edit.toggle()
                }
                .buttonStyle(BorderlessButtonStyle())
            }
            
            ForEach(0..<multiArray.count, id:\.self ){ i in
                Section { // 增加分组标识区分不同子数组
                    ForEach(multiArray[i], id:\.self ){ string in
                        Text(string)
                    }
                } header: {
                    Text("第\(i+1)组")
                }
            }
            .onMove(perform: moveOuterArray)
            
        }
        .environment(\.editMode, .constant(edit ? .active : .inactive))
    }
}

func moveOuterArray(from source: IndexSet, to destination: Int) {
    multiArray.move(fromOffsets: source, toOffset: destination)
}

方案2:实现内层单个元素移动

如果需要移动子数组内部的单个元素,需要将onMove修饰符绑定到内层ForEach,同时修改移动逻辑处理指定外层索引的子数组:

@State var multiArray = [["String_1_1", "String_1_2"],["String_2_1", "String_2_2"]]
@State var edit: Bool = false

var body: some View {
    NavigationStack{
        List {
            Section{
                Button(edit ? "完成" : "编辑") {
                    edit.toggle()
                }
                .buttonStyle(BorderlessButtonStyle())
            }
            
            ForEach(0..<multiArray.count, id:\.self ){ i in
                Section {
                    ForEach(multiArray[i], id:\.self ){ string in
                        Text(string)
                    }
                    .onMove { source, destination in
                        moveInnerArray(from: source, to: destination, outerIndex: i)
                    }
                } header: {
                    Text("第\(i+1)组")
                }
            }
        }
        .environment(\.editMode, .constant(edit ? .active : .inactive))
    }
}

func moveInnerArray(from source: IndexSet, to destination: Int, outerIndex: Int) {
    multiArray[outerIndex].move(fromOffsets: source, toOffset: destination)
}

扩展:跨子数组移动单个元素

如果需要支持把元素从一个子数组移动到另一个子数组,需要额外做数据打平处理,或者使用拖拽手势自定义移动逻辑,核心思路是:

  • 给每个元素绑定全局唯一标识
  • 记录拖拽起始位置对应的外层、内层索引
  • 释放时更新对应位置的数组元素,删除原位置元素、插入到目标位置

内容的提问来源于stack exchange,提问作者M_M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 22:36:05