我一直在尝试找出如何将图像的文件名拖放到SwiftUI视图中。
代码片段如下:
struct MainView: View, DropDelegate {
@ObservedObject var userState : UserState
var body : some View {
Group {
if (self.userState.editing) {
BlackoutView()
} else {
DropView()
}
}
.frame(minWidth: 320, idealWidth: 640, maxWidth: .infinity, minHeight: 240, idealHeight: 480, maxHeight: .infinity, alignment: .center)
.onDrop(of: [(kUTTypeImage as String), "public.pdf"], delegate: self)
}
func dropUpdated(info: DropInfo) -> DropProposal? {
let proposal = DropProposal.init(operation: .copy)
return proposal
}
func performDrop(info: DropInfo) -> Bool {
print("perform drop")
userState.editing = true
return true
}
}
当我将图像拖放到应用程序上时,它将运行performDrop
。如何获取放置到应用程序中的图像的文件名?
它在macOS上运行。
答案 0 :(得分:1)
花了一个多小时与api进行斗争(文档几乎不存在),这对我有用:
// The onDrop registration
.onDrop(of: [(kUTTypeFileURL as String)], delegate: self)
...
func performDrop(info: DropInfo) -> Bool {
guard let itemProvider = info.itemProviders(for: [(kUTTypeFileURL as String)]).first else { return false }
itemProvider.loadItem(forTypeIdentifier: (kUTTypeFileURL as String), options: nil) {item, error in
guard let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil) else { return }
// Do something with the file url
// remember to dispatch on main in case of a @State change
}
return true
}
请注意,我已省略任何验证,因此此代码从所有已删除的文件中获取第一个URL