How to set a custom preview image for SwiftUI Drag and Drop on macOS

Is it possible to change the drag and drop preview image. I am currently using the following code but the imagePreviewHandler never gets called and the image is always just a rendering of the visible portion of the gridView

Code Block
...
grid
.drag(if: isDraggable, data: {
                        return self.dragData()
                    })
...


Code Block
    func dragData()->NSItemProvider{
        
        let itemProvider = NSItemProvider(object: fileService )
        
        itemProvider.previewImageHandler = { (handler, _, _) -> Void in
            os_log("previewImageHandler called")
            if let image = NSImage(named: "film") {
                handler?(image as NSSecureCoding?, nil)
            } else {
                let error = NSError(domain:"", code:001, userInfo:[ NSLocalizedDescriptionKey: "Unable to create preview image"])
                handler?(nil, error)
            }
        }
        return itemProvider
    }


Code Block
struct Draggable: ViewModifier {
    let condition: Bool
    let data: () -> NSItemProvider
    @ViewBuilder
    func body(content: Content) -> some View {
        if condition {
            content.onDrag(data)
        } else {
            content
        }
    }
}
extension View {
    public func drag(if condition: Bool, data: @escaping () -> NSItemProvider) -> some View {
        self.modifier(Draggable(condition: condition, data: data))
    }
}

Replies

But you'll find that if you explicitly call provider.loadPreviewImage(...) your previewImageHandler will actually get called.

However, even though the previewImageHandler can provide a perfectly good image, even after it returns the new data SwiftUI seems to ingore it and continues to use the image from the original view! :(

I too would like an answer to the question: Why does SwiftUI ignore attempts to add a custom drag image?