首页 > 解决方案 > SwiftUI list 移动和选择行

问题描述

我正在尝试对列表行执行两个操作,如下图所示

在此处输入图像描述

第一个是通过使用“ForEach”和“.onMove”使其移动和重新排列并完成,第二个是通过使用“List”和“selection”选项进行多选行,这样也完成了. 问题是我不能将这两个选项结合起来,因为其中一个使用“List”,另一个使用“ForEach”,当我这样做时,会发生意外行为。那么有没有人可以帮助我解决这个问题,拜托。

标签: swiftui-list

解决方案


这是一个可能的解决方案,如何结合选择和 onMove。

struct ContentView : View {
        
    @State var items = ["Dave", "Tom", "Jeremy", "Luke", "Phil"]
    
    @State var selectedItems : Set<String> = Set<String>()
    
    var body : some View {
        NavigationView {
            List(selection: $selectedItems) {
                ForEach(items, id:\.self) { item in
                    Text(item).tag(item)
                }.onMove(perform: move)
            }
            .navigationBarItems(trailing: EditButton())
        }
    }
    
    func move(from source: IndexSet, to destination: Int) {
        items.move(fromOffsets: source, toOffset: destination)
    }
}

推荐阅读