With the release of iOS-11, Apple introduced Drag and Drop in UITableView
and 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.
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 [UICollectionViewDragDelegate](https://developer.apple.com/documentation/uikit/uicollectionviewdragdelegate)
protocol.
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:
collectionView(_:itemsForBeginning:at:)
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 [UICollectionViewDropDelegate](https://developer.apple.com/documentation/uikit/uicollectionviewdropdelegate)
protocol.
The only required method of this protocol is:
collectionView(_:performDropWith:)
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 viewDidLoad()
.
collectionView.dropDelegate = self
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
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:
Each item that needs to be dragged must be represented as an object of UIDragItem
.
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 indexPath
.
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..
collectionView(_:itemsForBeginning:at:)
method of UICollectionViewDragDelegate
.
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 String
objects as the data source to the collection view. So, item will correspond to a String
value.
NSItemProvider
using the item
extracted in Line 3. item
is casted into NSString
because **NSItemProvider**
accepts an object and swift String
is a value-type not an object-type.UIDragItem
object from itemProvider
.
Line 6 — localObject
is 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.
dragItem
.In case you want to ignore the drag, return an empty array.
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.
collectionView(_:itemsForAddingTo:at:point:)
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 collectionView(_:itemsForBeginning:at:)
.
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.
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:
collectionView(_:dropSessionDidUpdate:withDestinationIndexPath:)
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:
nil
if the drag activity started in a different app.So here is what the above code speaks:
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 UICollectionViewDropDelegate
.
That is: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 draggeddestinationIndexPath
— The index path at which to insert the item in the collection view. It is an optional value. nil
is 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 itemsAlso, when incorporating items, use drop(_:to:)
or 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:
destinationIndexPath
is 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.operation
— move/copy/forbidden/cancel
.In case your drop proposal is **cancel/forbidden**
, 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:)](https://developer.apple.com/documentation/uikit/uicollectionview/1618045-performbatchupdates)
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:
localObject
property 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.itemProvider
property to fetch the data.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:
move
as your drop proposal in [tableView(_:dropSessionDidUpdate:withDestinationIndexPath:)](https://developer.apple.com/documentation/uikit/uitableviewdropdelegate/2897302-tableview)
to support reordering.[tableView(_:canMoveRowAt:)](https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614927-tableview)
and [tableView(_:moveRowAt:to:)](https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614867-tableview)
methods of UITableViewDataSource
.
[tableView(_:performDropWith:)](https://developer.apple.com/documentation/uikit/uitableviewdropdelegate/2897427-tableview)
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.
Note: the destinationIndexPath
obtained from coordinator
in 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 sourceIndexPath
?
Well, we have an answer for that too.
[sourceIndexPath](https://developer.apple.com/documentation/uikit/uicollectionviewdropitem/2897392-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.
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.
We can control the reordering speed for a better user experience using reorderingCadence of type enum UICollectionViewReorderingCadence on collection view object.
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 viewDidLoad()
.
collectionView.reorderingCadence = .fast
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:)](https://developer.apple.com/documentation/uikit/uicollectionviewdragdelegate/2897459-collectionview)
method of UICollectionViewDropDelegate
.
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:
Feel free to leave comments in case you have any doubts.