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.
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.
Very simple implementation of drag&drop stack view.
drag-and-drop zone in Swift
- Add conformance to
NSDraggingDestinationto your subclass declaration if necessary (not needed for
NSImageViewbecause it already conforms to the protocol)
- Declare an array of accepted types (at least
- Register these types with
- Return an
NSDragOperationfrom these methods
- Get the file(s) path(s) from the
In my example I’ve added a function to check if the file extension is amongst the ones we want.