我一直在尝试在SwiftUI中的List
上实现拖放。我要做的就是在List
上拖一行,然后放到同一个List
中的一行上,就像iOS
上的Remainders应用程序一样。
注意:重要的是要注意,我并不是要重新排列列表,而是要使被删除的项成为该行的“子”项。
import SwiftUI
import UniformTypeIdentifiers
struct Item: Identifiable {
let id = UUID()
let title: String
}
struct EditListView: View {
@State private var items: [Item] = [
Item(title: "Apple"),
Item(title: "Banana"),
Item(title: "Papaya"),
Item(title: "Mango")
]
var body: some View {
VStack {
List {
ForEach(items) { item in
Text(item.title)
}
.onDrop(of: [UTType.text], delegate:dropDelegate() )//doesn't work
.onDrag{
NSItemProvider(item: .some(URL(string: "item")! as NSSecureCoding), typeIdentifier: String() )
}
}
Text("Drop Item Here..")
.fontWeight(.heavy)
.onDrop(of: [UTType.text], delegate:dropDelegate() )//works
}
}
}
class dropDelegate: DropDelegate {
func performDrop(info: DropInfo) -> Bool {
print("drop success")
return true
}
}
使用Text
是可行的。
在列表行上拖放失败。
发布于 2021-11-19 14:01:39
看起来你的代码有两个问题。
First:web上的许多文章报告说,drop在List组件上不起作用,但您可以用ScrollView替换List。然后将调用drop方法。
第二个:如果你想逐项应用一个action,你必须将drop方法移到foreach中。
在更新后的代码中,我刚刚添加了一个单元格样本,你可以很容易地自己重现一个单元格效果:
struct Sample: View {
@State private var items: [Item] = [
Item(title: "Apple"),
Item(title: "Banana"),
Item(title: "Papaya"),
Item(title: "Mango")
]
var body: some View {
VStack {
ScrollView {
ForEach(items) { item in
SampleCell(item: item)
.onDrop(of: [UTType.text], delegate:dropDelegate() )
.onDrag{
NSItemProvider(item: .some(URL(string: "item")! as NSSecureCoding), typeIdentifier: String() )
}
}
}
Text("Drop Item Here..")
.fontWeight(.heavy)
.onDrop(of: [UTType.text], delegate:dropDelegate() )//works
}
}
}
struct SampleCell: View {
var item : Item
var body: some View {
HStack {
Text(item.title).padding()
Spacer()
}.frame(maxWidth:.infinity, minHeight: 60)
.background(Color.gray)
}
}
https://stackoverflow.com/questions/69931818
复制相似问题