我有一个简单的应用程序,我希望能够改变项目的顺序,当我做一个长按像在Safari与选项卡。我知道我需要使用.onLongPressGesture
,但是我不能实现它。
import SwiftUI
struct HomeView: View {
struct Item: Identifiable {
var id = UUID()
var name: String
var color: Color
}
@State var items = [
Item(name: "Item 1", color: .red),
Item(name: "Item 2", color: .green),
Item(name: "Item 3", color: .blue)
]
var body: some View {
List {
ForEach(items, id: .id) { item in
Text(item.name)
.frame(maxWidth: .infinity)
.padding()
.background(item.color)
.foregroundColor(.white)
}
.onDelete(perform: deleteItem)
}
}
func deleteItem(at offsets: IndexSet) {
items.remove(atOffsets: offsets)
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
代替.onLongPressGesture
,你可以使用.onMove
来改变项目的顺序-在iOS中,当使用.onMove
时,长按已经是重新排序的要求。
var body: some View {
List {
ForEach(items, id: .id) { item in
Text(item.name)
.frame(maxWidth: .infinity)
.padding()
.background(item.color)
.foregroundColor(.white)
}
.onDelete(perform: deleteItem)
.onMove(perform: move)
}
}
func move(from source: IndexSet, to destination: Int) {
items.move(fromOffsets: source, toOffset: destination)
}
(基于链接的代码)
我希望这对你有帮助。