With the release of iOS-11, Apple introduced Drag and Drop in
UICollectionView with a specialized API that works on the concept of Interactions (something like gestures).
Table view and collection view have similar APIs to support drag and drop with some small differences.
Drag and drop is supported in both iPhone as well as iPad. On iPad, user can drag-drop within multiple apps. But for iPhone this support is provided only within a single app.
We’ll be discussing how drag and drop works in collection views and the same will be applicable to table views. I’ll point out the differences in table view wherever required. So don’t worry about it. You’ll get it working for both collection view as well as the table view.
Let’s get started 🚀
Adopting drag and drop in collection view is a multi-step process. We’ll go through each and every detail required to integrate dragging and dropping elements in the collection view.
To enable drags, the custom object must conform to
It contains multiple methods that can be implemented to customize the drag behaviour of the collection view.
The only required method of this protocol you need to put in place to support drag behaviour is:
We’ll look into the method details in upcoming sections.
Also, set the
dragDelegate delegate object of collection view in
viewDidLoad() to manage the dragging of items from it.
collectionView.dragDelegate = self
To enable drops, the custom object must conform to
The only required method of this protocol is:
You can implement other methods as needed to customize the drop behavior of your collection view.
Also, assign your custom delegate object to the
dropDelegate property of your collection view in
collectionView.dropDelegate = self
Enabling Drag Interaction
To enable/disable drags , you can customize
dragInteractionEnabled property of your collection view.
The default value of this property is true on iPad and false on iPhone.
So, set it to true to enable content dragging from your collection view if you are providing drag-drop support in iPhone.
collectionView.dragInteractionEnabled = true
Dragging a Single Item
Now that we have configured our collection view to support drags and drops, its time to actually write the code that will make it happen.
Let’s start with the introduction to some important classes required to support drags and drops. Here we go:
- NSItemProvider — An item provider for conveying data or a file between processes during drag and drop.
- UIDragItem — A representation of an underlying data item being dragged from one location to another.
Each item that needs to be dragged must be represented as an object of
To allow dragging of items from your collection view, implement the only required method of
UICollectionViewDragDelegate and return one or more
UIDragItem objects for the item at the specified
OMG ! 😯 What was that? Too much to understand..!!!
Don’t worry. We’ll go through each step in the below code:
Let’s see what the code says..
- Line 1 — implement the
- Line 3 — Get the data corresponding to the picked item’s
indexPath. Use the model that you are using as collection view’s data source.
Here I have used an array of
Stringobjects as the data source to the collection view. So, item will correspond to a
- Line 4 — Create an object of
itemextracted in Line 3.
itemis casted into
NSItemProvideraccepts an object and swift
Stringis a value-type not an object-type.
- Line 5 — Create a
- Line 6 —
localObjectis the custom object associated with the drag item. It is only available to the app that initiates the drag activity.
This is optional but makes it faster to drag and drop content within the same app.
- Line 7 — Return an array of
In case you want to ignore the drag, return an empty array.
Dragging Multiple Items
We have seen how to drag a single item from collection view. What if I want to drag multiple items in one go?
Well, we have a
UICollectionViewDragDelegate method to achieve that.
This method adds the specified items to an existing drag session.
Items are added to the active drag session with a single tap. If you do not implement this method, taps in the collection view trigger the selection of items or other behaviors.
It has the similar implementation as that of
You can add your own constraints as per your requirement.
Example: ignore adding the item if it already exist in collection view in which you are dropping it. In this case return an empty array.
Drop Proposal — UICollectionViewDropProposal
We picked the item and then dragged it. Now, we cannot just keep on dragging the item for long. What to do with it now? Where to drop it? What will happen when I drop the item?
All of these questions point to a very specific one :
“How do you intend to handle the drop at a specified location?
Do you want to copy the item or just move it to a new position?
Or do you want to forbid the movement in some specific conditions?
Oh no..!! Can I just cancel it?”
Well well well..!!! There is a single answer to all your question — Drop Proposal. A drop proposal as the name suggests is the proposal of how you intend to handle the drop at a specific location when the user lifts his finger.
UIDropProposal — A configuration for the behavior of a drop interaction, required if a view accepts drop activities.
Each proposal defines an operation — enum UIDropOperation, that determines how a drag and drop activity resolves when the user drops a drag item. An operation is defined by can be of type:
cancel— no data should be transferred, canceling the drag.
forbidden— although a move or copy operation is typically legitimate in this scenario, the drop activity is not allowed.
copy— data represented by the drag items should be copied to the destination view.
move— data represented by the drag items should be moved, not copied.
UICollectionViewDropProposal — A subclass of UIDropProposal dedicated to collection views for handling drop proposals.
A collection view proposal also defines an optional intent — enum UICollectionViewDropIntent, that determines how to incorporate the content into the collection view. You can insert the content between items or add it to an existing item. Possible values of an intent are:
unspecified— No drop proposal was specified.
insertAtDestinationIndexPath— Insert the dropped items at the specified index path.
insertIntoDestinationIndexPath— Incorporate the dropped items into the item at the specified index path.
The collection view uses
intent information to provide appropriate visual feedback to the user.
Now that we know what a drop proposal is, the thing we need to figure out now is how and where to implement it.
UICollectionViewDropDelegate provides a method where you can specify the drop proposal you want to use, that is:
While the user is dragging content, the collection view calls this method repeatedly to determine how you would handle the drop if it occurred at the specified location.
Because this method is called repeatedly while the user drags over the collection view, your implementation should return as quickly as possible.
In the above code I have used 2 properties:
- localDragSession — The local drag session is
nilif the drag activity started in a different app.
- hasActiveDrag — A Boolean value indicating whether items were lifted from the collection view and have not yet been dropped.
So here is what the above code speaks:
- Line 16 — If the drag activity started in another app, forbid the drop.
- Line 7 — Else, if the item was lifted from the same collection view in which you are dropping it, then move (reorder) it from source to destination index path.
- Line 11 — Otherwise, if you are dropping it in another collection view, then copy the item to the destination index path.
Handling Drop — Copy
After being clear about how we intend to handle the drop, let’s look at the implementation details of what we need to do once the actual drop is made.
To allow dropping of items in your collection view, implement the only required method of
collectionView(_:performDropWith:) — Tells your delegate to incorporate the drop data into the collection view.
This method provides you with a UICollectionViewDropCoordinator object that you can use to handle the drop. Using
coordinator, you can fetch the below items to update your collection view’s data source:
items— The items being dragged
destinationIndexPath— The index path at which to insert the item in the collection view. It is an optional value.
nilis returned in case the item is inserted in an empty collection view or at the end of the collection view.
proposal— The current proposal for how to incorporate the dropped items
Also, when incorporating items, use
drop(_:toItemAt:) methods of the
coordinator object to animate the transition from the drag item's preview to the corresponding item in your collection view.
Let’s look at some code now.
The above code is pretty straight forward:
destinationIndexPathis fetched from the
coordinator. In case it is
nil, the last index path of the collection view is used as the destination to drop the item.
- Take appropriate action to update the collection view based on the drop proposal’s
In case your drop proposal is
collectionView(_:performDropWith:) won’t be called for handling the drops and hence you need not do anything special about it.
If the proposed handling is
move , we need to reorder the items. We’ll discuss more about reordering in the next section.
In this section, let’s have a look at how to handle drop if we intend to
copy the items.
You can use collection view’s
performBatchUpdates(_:completion:) to make changes in the collection view.
You can use this method in cases where you want to make multiple changes to the collection view in one single animated operation, as opposed to in several separate animations.
Deletes are processed before inserts in batch operations. This means the indexes for the deletions are processed relative to the indexes of the collection view’s state before the batch operation, and the indexes for the insertions are processed relative to the indexes of the state after all the deletions in the batch operation.
Here is how you can do it:
To get the data corresponding to dragged item, you can use one of the below options:
localObjectproperty of the drag item can be used if it is set. It will be available if the content is originated from elsewhere in your app.
- Also, you can use the drag item’s
itemProviderproperty to fetch the data.
Handling Drop — Reordering
Reordering of the cells occur when the drop proposal is specified as — move.
Reordering — Moving an item from source index path to destination index path within same/different collection view or table view as per your requirement.
I am explicitly referring to table view here because table view and collection view handle reordering a bit differently. We’ll discuss both of them here.
In table views, reordering functionality is already available since a long time. And the good thing is we can continue using that 😅. No need to do anything special to support reordering in table views. You just need to:
moveas your drop proposal in
tableView(_:dropSessionDidUpdate:withDestinationIndexPath:)to support reordering.
tableView(_:performDropWith:) won’t be called for handling drops if the above
UITableViewDataSource methods are implemented.
In collection views, reordering is handled in the same manner as copying. The only difference is — in copying you were inserting a brand new item at the destination index path, but in reordering you need to delete an item from source index path and insert it at the destination index path.
The logic is changed a bit, rest everything remains same.
destinationIndexPath obtained from
collectionView(_:performDropWith:) could be the number of items in collection view if you try to reorder the item to the end of the collection view. In case of reordering, number of items in collection view remain same. So you need to handle that explicitly as it might throw
Array index out of bounds runtime error.
Oh Wait ! I have
destinationIndexPath , but from where do I get
Well, we have an answer for that too.
sourceIndexPath can be obtained corresponding to each item fetched using
coordinator . If the item is originated from the same collection view, this property contains the item’s original index path.
In the above code, a single item is reordered. You can do it for multiple items as per your requirement.
Reordering Speed — reorderingCadence
In case of reordering, when you drag an item over a collection view which accepts a drop, the collection view provides an appropriate visual feedback to the user — shifting/reordering the cells to accomodate a new one.
reorderingCadence can have these possible values:
immediate— Items are reordered into place immediately. (default value)
fast— Items are reordered quickly, but with a short delay.
slow— Items are reordered after a delay.
Set the appropriate value of
reorderingCadence on your collection view object in
collectionView.reorderingCadence = .fast
Drag Preview — UIDragPreviewParameters
When an item is lifted, the collection view uses the item’s visible bounds to create the preview by default. In case you want to customize the appearance of the item, you can achieve it through preview parameters.
UIDragPreviewParameters — A set of parameters for adjusting the appearance of a drag item preview.
The parameters specify different visual aspects of the preview, including the background color and the visible area of the view associated with the preview.
In case you don’t want to make any changes to the drag preview, don’t implement this method or return
nil if you implement it.
To customize the drag preview, implement
collectionView(_:dragPreviewParametersForItemAt:) method of
That’s it. That’s all you need to get drop-drop working in collection and table view. Go on..give it a try !!
You can download the sample project from here.
Don’t forget to read my other articles:
- Everything about Codable in Swift 4
- Everything you’ve always wanted to know about notifications in iOS
- Color it with GRADIENTS — iOS
- All you need to know about Today Extensions (Widget) in iOS 10
- UICollectionViewCell selection made easy..!!
Feel free to leave comments in case you have any doubts.