Drag & Drop Images to Custom View (i.e. UIImageView)

Derek Kim
5 min readNov 13, 2023

Hello, this is Derek!

Today I’d like to share with you guys on how to implement Drag & Drop Image to the Custom View.

Before I even begin, I wondered, why do we even need to drag-and-drop an image in the first place in iOS device? It’s not like we have split view in our device which we would be able to drag an image from one app to another.

Well, I thought wrong, and it was an oversight on my end. Most commonly used example is Apple’s ability to cutout an image and be able to drag this image to another application. I’ll show you what I mean in more detail soon.

Prior to iOS 15, drag-and-drop activities on iPhone was only allowed within the app itself and not between two different apps. Now with continuous gestures, we can drag-and-drop an image from one app to another.

So there are two parts to this. Dragging and Dropping. While we will be looking into both functionality, let’s start by digging into drop functionality, because we will drag an image from elsewhere, like Photo app, and the drag implementation will most likely already be setup from their end.

To add drop interaction, we must declare UIDropInteraction, delegate it to self, and conform to it’s delegate.

let dropInteraction = UIDropInteraction(delegate: self)
imageView.addInteraction(dropInteraction)

imageView.isUserInteractionEnabled = true

It is crucial that you set .isUserInteractionEnabled to true, otherwise your imageView will not be able to notice the dropped item.

Once you have this setup, XCode will complain that you will need to conform to expected type UIDropInteractionDelegate. I usually like to conform to delegates in an extension.

First, you would want to handle what type of dragged item you would like to handle, and the count of it (if necessary).

extension ViewController: UIDropInteractionDelegate {

func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.hasItemsConforming(toTypeIdentifiers: [UTType.image.identifier]) && session.items.count == 1
}

}

--

--