如何在 SwiftUI 上添加拖放功能以重新排序行? 只是一个没有“编辑模式”的干净解决方案。 Here一个例子:
更新
我在 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)")
}
}
}
}
最佳答案
要在用户长按某个项目时将列表置于编辑模式,您可以使用状态标志并相应地设置编辑环境值。让标志变化动画化是很重要的,这样才不会显得很奇怪。
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
}
}
}
关于swiftui - 在 SwiftUI 上通过拖放进行列表重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56790502/