swiftui - 拖放列表以在 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)")
}
}
}
}
解决方案
要在用户长按某个项目时将列表置于编辑模式,您可以使用状态标志并相应地设置编辑环境值。重要的是使标志更改动画化,以免看起来很奇怪。
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
}
}
}
推荐阅读
- html - 使用Bootstrap将div中的项目对齐到较大设备上的水平方向和较小设备上的垂直方向?
- r-markdown - 从 HTML 转换为 PDF 时用 Rmd 编写的幻灯片缺少页面
- php - 使用 ajax 将值从一个 PHP 页面传递到另一个页面
- css - 跨多个元素的连续边框
- json - 我应该通过 JSON 发送图像吗
- python - 如何在tensorflow中使用预批处理数据和不同形状的数据
- javascript - 修改 Selectize.js 库以允许编辑选定的选项
- typescript - 扩展类型的原型
- python - Python - OSError:[WinError 10013] 试图以访问权限禁止的方式访问套接字
- java - 如何根据原始输入对哈希表/枚举进行排序