实际上,在SwiftUI中处理多个项目的拖放时,您不需要
[NSItemProvider]
。由于您必须在自己的选择管理器中跟踪多个选定项目,因此在生成自定义拖动预览和处理拖放时,请使用该选择。将一个新的MacOS App项目的
ContentView
替换为下面的所有代码。这是一个完整的工作示例,演示如何使用SwiftUI拖放多个项目。要使用它,您必须选择一个或多个项目以启动拖动,然后可以将它们拖到任何其他未选定的项目上。在控制台上打印出了拖放操作的结果。我相当快地把这些东西组合起来了,所以我的示例可能存在一些低效之处,但它似乎工作得很好。
import SwiftUI
import Combine
struct ContentView: View {
private let items = ["Item 0", "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7"]
@StateObject var selection = StringSelectionManager()
@State private var refreshID = UUID()
@State private var dropTargetIndex: Int? = nil
var body: some View {
VStack(alignment: .leading) {
ForEach(0 ..< items.count, id: \.self) { index in
HStack {
Image(systemName: "folder")
Text(items[index])
}
.opacity((dropTargetIndex != nil) && (dropTargetIndex == index) ? 0.5 : 1.0)
.id(refreshID)
.onDrag { itemProvider(index: index) } preview: {
DraggingPreview(selection: selection)
}
.onDrop(of: [.text], delegate: MyDropDelegate(items: items,
selection: selection,
dropTargetIndex: $dropTargetIndex,
index: index) )
.padding(2)
.onTapGesture { selection.toggle(items[index]) }
.background(selection.isSelected(items[index]) ?
Color(NSColor.selectedContentBackgroundColor) : Color(NSColor.windowBackgroundColor))
.cornerRadius(5.0)
}
}
.onReceive(selection.objectWillChange, perform: { refreshID = UUID() } )
.frame(width: 300, height: 300)
}
private func itemProvider(index: Int) -> NSItemProvider {
if selection.isSelected(items[index]) {
return NSItemProvider(object: items[index] as NSString)
} else {
return NSItemProvider()
}
}
}
struct DraggingPreview: View {
var selection: StringSelectionManager
var body: some View {
VStack(alignment: .leading, spacing: 1.0) {
ForEach(selection.items, id: \.self) { item in
HStack {
Image(systemName: "folder")
Text(item)
.padding(2.0)
.background(Color(NSColor.selectedContentBackgroundColor))
.cornerRadius(5.0)
Spacer()
}
}
}
.frame(width: 300, height: 300)
}
}
struct MyDropDelegate: DropDelegate {
var items: [String]
var selection: StringSelectionManager
@Binding var dropTargetIndex: Int?
var index: Int
func dropEntered(info: DropInfo) {
dropTargetIndex = index
}
func dropExited(info: DropInfo) {
dropTargetIndex = nil
}
func validateDrop(info: DropInfo) -> Bool {
if !selection.isSelected(items[index]) {
return info.hasItemsConforming(to: [.text])
} else {
return false
}
}
func dropUpdated(info: DropInfo) -> DropProposal? {
if !selection.isSelected(items[index]) {
let dragOperation = NSEvent.modifierFlags.contains(NSEvent.ModifierFlags.option) ? DropOperation.copy : DropOperation.move
return DropProposal(operation: dragOperation)
} else {
return DropProposal(operation: .forbidden)
}
}
func performDrop(info: DropInfo) -> Bool {
let dropProposal = dropUpdated(info: info)
if dropProposal?.operation != .forbidden {
let dropOperation = dropProposal!.operation == .move ? "Move" : "Copy"
if selection.selection.count > 1 {
for item in selection.selection {
print("\(dropOperation): \(item) Onto: \(items[index])")
}
} else {
if let item = info.itemProviders(for: ["public.utf8-plain-text"]).first {
item.loadItem(forTypeIdentifier: "public.utf8-plain-text", options: nil) { (data, error) in
if let data = data as? Data {
let item = NSString(data: data, encoding: 4)
print("\(dropOperation): \(item ?? "") Onto: \(items[index])")
}
}
}
return true
}
}
return false
}
}
class StringSelectionManager: ObservableObject {
@Published var selection: Set<String> = Set<String>()
let objectWillChange = PassthroughSubject<Void, Never>()
var items: [String] {
return Array(selection)
}
func isSelected(_ value: String) -> Bool {
return selection.contains(value)
}
func toggle(_ value: String) {
if isSelected(value) {
deselect(value)
} else {
select(value)
}
}
func select(_ value: String?) {
if let value = value {
objectWillChange.send()
selection.insert(value)
}
}
func deselect(_ value: String) {
objectWillChange.send()
selection.remove(value)
}
}
onDrag
在 iPad 上支持拖动List
的多个项目,但在 iPhoneOS(v14.x)或 macOS(v11.x 以上)上似乎不支持。如果在 iOS 15 和 macOS 12 上没有修复的话,可能需要将其报告为错误。 - Dad