有的时候,我们希望能通过拖拽List上的项目。调整List的顺序,用下面的代码可以简单的实现。


import SwiftUI
struct ContentView: View {
@State private var fruits = ["Point1", "Point2", "Point3"]
@State private var isEditable = false
var body: some View {
List {
ForEach(fruits, id: \.self) { user in
HStack(spacing: 20) {
Text(user).foregroundColor(.white)
.font(.largeTitle)
.frame(width: 200, height: 200).background(Color.green)
ScrollView(.horizontal) {
HStack(spacing: 20) {
ForEach(0..<10) {
Text("Item \($0)")
.foregroundColor(.white)
.font(.largeTitle)
.frame(width: 200, height: 200)
.background(Color.red)
}
}
}.allowsHitTesting(false) // 非常重要,阻止ScrollView的点击事件,否则会和List的冲突。
}
} .onMove(perform: move)
// 长按时改变List的编辑模式。
.onLongPressGesture {
withAnimation {
self.isEditable = true
}
}
}
// 通过设定environment的 editMode的值,来改变List的编辑模式。
.environment(\.editMode, isEditable ? .constant(.active) : .constant(.inactive))
}
func move(from source: IndexSet, to destination: Int) {
fruits.move(fromOffsets: source, toOffset: destination)
withAnimation {
isEditable = false
}
}
}