使用自定义类型标识符拖放不起作用

Pro*_*in8 5 macos swiftui

我正在尝试使用自定义类型标识符在 macOS 上实现拖放以避免冲突,但它似乎不起作用。首先,这是一个具有公共和已知标识符的工作示例:

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
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

在本例中,您可以将上面的图像拖入拖放区,它会打印出提供者。现在,仅仅改变就typeIdentifier破坏了一切。

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
            }
}
Run Code Online (Sandbox Code Playgroud)

现在这不起作用。在这里使用相同的常量,所以它不是字符串不匹配。又一个 SwiftUI 错误?

Asp*_*eri 8

typeIdentifier上面的in 不仅仅是一个唯一的字符串,它必须是 UTI

如果你想使用一些自定义应用程序特定的 UTI(如果你真的需要它,请三思),那么你必须根据 Apple 规则注册一个,从

<key>UTExportedTypeDeclarations</key>
        <array>
            <dict>
                <key>UTTypeIdentifier</key>
                <string>com.procrastin8.plzwork</string>
                ...
Run Code Online (Sandbox Code Playgroud)

在应用程序中 Info.plist

请参阅声明新的统一类型标识符中的详细信息

以及技术问答 QA1796 中的广泛收集