我实现了一个简单的拖放来重新排序 VStack/Scrollview 中的项目
根据这个解决方案
我将当前拖动的项目存储在名为的属性中draggingItem
并将不透明度设置为 0,具体取决于它是否为零。
当 DropDelegate 中的 PerformDrop 被调用时我设置draggingItem
返回 nil 以使相应的项目再次可见。
在两种情况下,performDrop 似乎不会被调用:
-
当项目处于 onDrag 状态,然后在原地释放而不移动时。
-
当项目被释放时,实际的放置区域会稍微偏移。
这导致该项目不再可见,因为draggingItem
不会再次设置为零。
关于更好的设置场所的任何想法draggingItem
回到零?
View:
struct ReorderingTestsView: View {
@State var draggingItem: BookItem?
@State var items: [BookItem] = [
BookItem(name: "Harry Potter"),
BookItem(name: "Lord of the Rings"),
BookItem(name: "War and Peace"),
BookItem(name: "Peter Pane")
]
var body: some View {
VStack{
ScrollView{
VStack(spacing: 10){
ForEach(items){ item in
VStack{
Text(item.name)
.padding(8)
.frame(maxWidth: .infinity)
}
.background(Color.gray)
.cornerRadius(8)
.opacity(item.id == draggingItem?.id ? 0.01 : 1) // <- HERE
.onDrag {
draggingItem = item
return NSItemProvider(contentsOf: URL(string: "\(item.id)"))!
}
.onDrop(of: [.item], delegate: DropViewDelegate(currentItem: item, items: $items, draggingItem: $draggingItem))
}
}
.animation(.default, value: items)
}
}
.padding(.horizontal)
}
}
删除视图委托:
struct DropViewDelegate: DropDelegate {
var currentItem: BookItem
var items: Binding<[BookItem]>
var draggingItem: Binding<BookItem?>
func performDrop(info: DropInfo) -> Bool {
draggingItem.wrappedValue = nil // <- HERE
return true
}
func dropEntered(info: DropInfo) {
if currentItem.id != draggingItem.wrappedValue?.id {
let from = items.wrappedValue.firstIndex(of: draggingItem.wrappedValue!)!
let to = items.wrappedValue.firstIndex(of: currentItem)!
if items[to].id != draggingItem.wrappedValue?.id {
items.wrappedValue.move(fromOffsets: IndexSet(integer: from),
toOffset: to > from ? to + 1 : to)
}
}
}
func dropUpdated(info: DropInfo) -> DropProposal? {
return DropProposal(operation: .move)
}
}
测试项目:
struct BookItem: Identifiable, Equatable {
var id = UUID()
var name: String
}