I noticed an issue with the drag and drop features in SwiftUI that are available since iOS 13.4. The drag and drop operation with the .onDrag and .onDrop modifiers works fine in the simulator, but on a real device (iPhone and iPad) you just see a transparent rect, instead of the view while dragging the view.
Does anyone have a solution to get the correct preview image while the view is dragged?
struct MainView: View {
@State var isDropTarget = false
var body: some View {
VStack{
Image(systemName: "doc.text")
.font(.system(size: 40))
.frame(width: 150, height: 150)
.onDrag { return NSItemProvider(object: "TestString" as NSString) }
Color.orange
.opacity(isDropTarget ? 0.5 : 1)
.onDrop(of: ["public.text"], isTargeted: $isDropTarget) { items in
for item in items {
if item.canLoadObject(ofClass: NSString.self) {
item.loadObject(ofClass: String.self) { str, _ in
print(str ?? "nil")
}
}
}
return true
}
}
}
While iOS 15 did not fix this bug in my testing, there is a new API that allows you to specify the preview View
to display: onDrag(_:preview:). You can recreate the view being dragged, in this case your Image
, for the preview.