swiftmacosswiftuidrag-and-dropdraggable

.dropDestination doesn't execute with my custom transferable type


I have defined

import SwiftUI
import UniformTypeIdentifiers

enum LayerType: String, Codable, RawRepresentable {
    case text
    case image
}

struct TransferableLayer: Identifiable, Hashable, Codable, Transferable {
    var id: UUID
    var type: LayerType
    
    init(id: UUID, type: LayerType) {
        self.id = id
        self.type = type
    }

    static var transferRepresentation: some TransferRepresentation {
        CodableRepresentation(contentType: .transferableLayer)
    }
}

extension UTType {
    static let transferableLayer = UTType(exportedAs: "co.customUTType.transferableLayer")
}

Note: I've added it in Exported Type Identifiers as well: enter image description here

Also I have LayersView where I assign .draggable attribute to Text:

 ForEach(Array(textLayers.enumerated()), id: \.element.id) { index, textLayer in
                    ...
                        Text(textLayer.text)
                           .draggable(TransferableLayer(id: textLayer.id, type: LayerType.text))
...
}

and I have PanelView where I added

.dropDestination(for: TransferableLayer.self) { droppedLayers, location in
   print("I'm inside dropDestination")
}

and print() code inside dropDestination doesn't call when I drag'n'drop my textLayer on Panel. But it shows preview properly and I see changes which I've made there.

UPD:

I've searched for similar question/answers on SO and found this one: Drag&Drop Custom Types with Transferable Protocol in Swiftui for macOS

Seems issue to Transferable protocol and how it works with Custom types on MacOS. BTW it works on Supported Destination as Mac Catalyst


Solution

  • CodableRepresentation is JSON, which is text.

    You are using an Exported Type Identifier that conforms to com.public.data.

    Use public.text instead.