Drag and Drop in a Custom View
March 26, 2020
This sample code project uses a UIImageView
instance to show how any instance or subclass of the UIView
class can act as a drag source or a drop destination.
To enable drag and drop, you add one or more interaction objects to a view. To provide or consume data, you implement the protocol methods in the interaction delegates.
Get Started
Deploy this sample code project on iPad, which supports drag and drop between apps. When you first launch this project’s built app, you see an image view containing an image. Use this app along with a second app that has images, such as Photos. For example, configure the iPad screen to Split View, with this app side by side with Photos. Then drag the image from this app into Photos, or drag an image from Photos into this app.
VCReorderableStackView
Very simple implementation of drag&drop stack view.
Reference: https://iosexample.com/a-simple-implementation-of-drag-drop-stack-view/
drag-and-drop zone in Swift
- Add conformance to
NSDraggingDestination
to your subclass declaration if necessary (not needed forNSImageView
because it already conforms to the protocol) - Declare an array of accepted types (at least
NSFilenamesPboardType
) - Register these types with
registerForDraggedTypes
- Override
draggingEntered
,draggingUpdated
andperformDragOperation
- Return an
NSDragOperation
from these methods - Get the file(s) path(s) from the
draggingPasteboard
array
In my example I’ve added a function to check if the file extension is amongst the ones we want.