使用自定义类型标识符进行拖放操作不起作用 [英] Drag and drop with custom type identifier doesn't work
问题描述
我正在尝试使用自定义类型标识符在macOS上实现拖放,以避免发生冲突,但这似乎不起作用.首先,这是一个具有 public 和已知标识符的工作示例:
I'm trying to achieve drag and drop on macOS with a custom type identifier to avoid collisions but it doesn't seem to work. First, here's a working example with a public and known identifier:
struct ReleaseView: View {
let id: Int
var body: some View {
GeometryReader { _ in
VStack(spacing: 16) {
Image(nsImage: NSImage(named: NSImage.networkName)!)
.contentShape(Rectangle())
.onDrag {
return NSItemProvider(item: "\(self.id)" as NSString, typeIdentifier: NSPasteboard.PasteboardType.string.rawValue)
}
DropZone()
}
}
}
}
struct DropZone: View {
@State var isDragging = false
var body: some View {
RoundedRectangle(cornerRadius: 16)
.stroke(style: StrokeStyle(lineWidth: 4, dash: [8, 8]))
.background(isDragging ? Color.secondary : Color.clear)
.frame(width: 100, height: 100)
.onDrop(of: [NSPasteboard.PasteboardType.string.rawValue], isTargeted: self.$isDragging) { itemProvider in
print(itemProvider)
return true
}
}
}
在此示例中,您可以将上面的图像拖动到放置区域中,它将打印出提供程序.现在,仅更改typeIdentifier
会破坏一切.
In this example, you can drag the image above into the drop zone and it will print out the provider. Now, merely changing the typeIdentifier
breaks everything.
static let sharedTypeIdentifier = "com.procrastin8.plzwork"
struct ReleaseView: View {
// skipping the unchanged bits
.onDrag {
return NSItemProvider(item: "\(self.id)" as NSString, typeIdentifier: sharedTypeIdentifier)
}
}
struct DropZone: View {
// skipping the unchanged bits
.onDrop(of: [sharedTypeIdentifier], isTargeted: self.$isDragging) { itemProvider in
print(itemProvider)
return true
}
}
现在这不起作用.在这里使用相同的常量,因此它不是字符串不匹配.只是另一个SwiftUI错误?
Now this doesn't work. Using the same constant here, so it's not a string mismatch. Just yet another SwiftUI bug?
推荐答案
上面的typeIdentifier
不仅仅是唯一的字符串,它必须是UTI .
The typeIdentifier
in above is not just a unique string, it must be UTI.
如果您要使用某些自定义应用程序的UTI(如果确实需要,请三思而后行),则必须根据Apple规则从
If you want to use some custom-application-specifc UTI (think twice if you really need it), then you have to register one according to Apple rules, starting from
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>com.procrastin8.plzwork</string>
...
在应用程序Info.plist
这篇关于使用自定义类型标识符进行拖放操作不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!