首页 > 解决方案 > 拖放列表以在 SwiftUI 上重新排序

问题描述

如何在 SwiftUI 上添加拖放以重新排序行?只是一个没有“编辑模式”的干净解决方案。这里有一个例子:

在此处输入图像描述

更新

我在The SwiftUI Lab上问了这个问题,作者回复了这段代码。仅适用于 iPad

    import SwiftUI

    struct Fruit: Identifiable {
        let id = UUID()
        let name: String
        let image: String
    }
            struct ContentView: View {
            @State var selection: Set<UUID> = []

            @State private var fruits = [
                Fruit(name: "Apple", image: "apple"),
                Fruit(name: "Banana", image: "banana"),
                Fruit(name: "Grapes", image: "grapes"),
                Fruit(name: "Peach", image: "peach"),
                Fruit(name: "Kiwi", image: "kiwi"),
            ]

            var body: some View {

                VStack {
                    NavigationView {
                        List(selection: $selection) {
                            ForEach(fruits) { fruit in
                                HStack {
                                    Image(fruit.image)
                                        .resizable()
                                        .frame(width: 30, height: 30)

                                    Text(fruit.name)
                                }
                            }
                            .onMove { _, _ in }
                        }
                        .navigationBarTitle("Fruits (Top)")
                    }
                }
            }
        }

标签: swiftui

解决方案


要在用户长按某个项目时将列表置于编辑模式,您可以使用状态标志并相应地设置编辑环境值。重要的是使标志更改动画化,以免看起来很奇怪。

struct ContentView: View {
    @State private var fruits = ["Apple", "Banana", "Mango"]
    @State private var isEditable = false

    var body: some View {
        List {
            ForEach(fruits, id: \.self) { user in
                Text(user)
            }
            .onMove(perform: move)
            .onLongPressGesture {
                withAnimation {
                    self.isEditable = true
                }
            }
        }
        .environment(\.editMode, isEditable ? .constant(.active) : .constant(.inactive))
    }

    func move(from source: IndexSet, to destination: Int) {
        fruits.move(fromOffsets: source, toOffset: destination)
        withAnimation {
            isEditable = false
        }
    }
}

推荐阅读