With the release of , Apple introduced in and with a specialized API that works on the concept of (something like gestures). iOS-11 Drag and Drop UITableView UICollectionView Interactions Table view and collection view have similar APIs to support drag and drop with some small differences. Drag and drop is supported in both as well as . On iPad, user can drag-drop within multiple apps. But for iPhone this support is provided only within a single app. iPhone iPad 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. UICollectionViewDragDelegate To enable , the custom object must conform to protocol. drags [UICollectionViewDragDelegate](https://developer.apple.com/documentation/uikit/uicollectionviewdragdelegate) It contains multiple methods that can be implemented to customize the drag behaviour of the collection view. The only of this protocol you need to put in place to support drag behaviour is: required method collectionView(_:itemsForBeginning:at:) We’ll look into the method details in upcoming sections. Also, set the delegate object of collection view in to manage the dragging of items from it. dragDelegate viewDidLoad() collectionView.dragDelegate = self UICollectionViewDropDelegate Protocol To enable , the custom object must conform to protocol. drops [UICollectionViewDropDelegate](https://developer.apple.com/documentation/uikit/uicollectionviewdropdelegate) The only of this protocol is: required method 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 property of your collection view in . dropDelegate viewDidLoad() collectionView.dropDelegate = self Enabling Drag Interaction To enable/disable drags , you can customize property of your collection view. dragInteractionEnabled The default value of this property is true on iPad and false on iPhone. So, set it to to enable content dragging from your collection view if you are providing drag-drop support in iPhone. true 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: An item provider for conveying data or a file between processes during drag and drop. NSItemProvider — A representation of an underlying data item being dragged from one location to another. UIDragItem — 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 and return one or more objects for the item at the specified . UICollectionViewDragDelegate UIDragItem 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.. Line 1 — implement the method of . collectionView(_:itemsForBeginning:at:) UICollectionViewDragDelegate Line 3 — Get the data corresponding to the picked item’s . Use the model that you are using as collection view’s data source.Here I have used an array of objects as the data source to the collection view. So, item will correspond to a value. indexPath String String Line 4 — Create an object of using the extracted in Line 3. is casted into because and swift is a value-type not an object-type. NSItemProvider item item NSString **NSItemProvider** accepts an object String Line 5 — Create a object from . UIDragItem itemProvider Line 6 — is the custom object associated with the drag item. It is only available to the app that initiates the drag activity. This is but makes it faster to drag and drop content within the same app. localObject optional Line 7 — Return an of . array dragItem 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 method to achieve that. UICollectionViewDragDelegate 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 . If you do not implement this method, taps in the collection view trigger the selection of items or other behaviors. single tap It has the similar implementation as that of . collectionView(_:itemsForBeginning:at:) You can add your own constraints as per your requirement. : ignore adding the item if it already exist in collection view in which you are dropping it. In this case return an empty array. Example 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 — 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. Drop Proposal. — A configuration for the behavior of a drop interaction, required if a view accepts drop activities. UIDropProposal Each proposal defines an — , 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: operation enum UIDropOperation — no data should be transferred, canceling the drag. cancel — although a move or copy operation is typically legitimate in this scenario, the drop activity is not allowed. forbidden — data represented by the drag items should be copied to the destination view. copy — data represented by the drag items should be moved, not copied. move — A subclass of UIDropProposal dedicated to collection views for handling drop proposals. UICollectionViewDropProposal A collection view proposal also defines an optional — , 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: intent enum UICollectionViewDropIntent — No drop proposal was specified. unspecified — Insert the dropped items at the specified index path. insertAtDestinationIndexPath — Incorporate the dropped items into the item at the specified index path. insertIntoDestinationIndexPath The collection view uses information to provide appropriate to the user. intent visual feedback Now that we know what a drop proposal is, the thing we need to figure out now is how and where to implement it. provides a method where you can specify the drop proposal you want to use, that is: UICollectionViewDropDelegate 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: — The local drag session is if the drag activity started in a different app. localDragSession nil — A Boolean value indicating whether items were lifted from the collection view and have not yet been dropped. hasActiveDrag So here is what the above code speaks: Line 16 — If the drag activity started in another app, the drop. forbid Line 7 — Else, if the item was lifted from the same collection view in which you are dropping it, then it from source to destination index path. move (reorder) Line 11 — Otherwise, if you are dropping it in another collection view, then the item to the destination index path. copy 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 . UICollectionViewDropDelegate That is: — Tells your delegate to incorporate the drop data into the collection view. collectionView(_:performDropWith:) This method provides you with a object that you can use to handle the drop. Using , you can fetch the below items to update your collection view’s data source: UICollectionViewDropCoordinator coordinator — The items being dragged items — The index path at which to insert the item in the collection view. It is an value. is returned in case the item is inserted in an empty collection view or at the end of the collection view. destinationIndexPath optional nil — The current proposal for how to incorporate the dropped items proposal Also, when incorporating items, use or methods of the object to animate the transition from the drag item's preview to the corresponding item in your collection view. drop(_:to:) drop(_:toItemAt:) coordinator Let’s look at some code now. The above code is pretty straight forward: is fetched from the . In case it is , the last index path of the collection view is used as the destination to drop the item. destinationIndexPath coordinator nil Take appropriate action to update the collection view based on the drop proposal’s — . operation move/copy/forbidden/cancel In case your drop proposal is , won’t be called for handling the drops and hence you need not do anything special about it. **cancel/forbidden** collectionView(_:performDropWith:) If the proposed handling is , we need to reorder the items. We’ll discuss more about reordering in the next section. **move** In this section, let’s have a look at how to handle drop if we intend to the items. **copy** You can use collection view’s to make changes in the collection view. [performBatchUpdates(_:completion:)](https://developer.apple.com/documentation/uikit/uicollectionview/1618045-performbatchupdates) 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: 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. localObject Also, you can use the drag item’s property to fetch the data. itemProvider Handling Drop — Reordering Reordering of the cells occur when the drop proposal is specified as — . move — Moving an item from source index path to destination index path within same/different collection view or table view as per your requirement. Reordering 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. , 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: In table views Return as your drop proposal in to support reordering. move [tableView(_:dropSessionDidUpdate:withDestinationIndexPath:)](https://developer.apple.com/documentation/uikit/uitableviewdropdelegate/2897302-tableview) Implement and methods of . [tableView(_:canMoveRowAt:)](https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614927-tableview) [tableView(_:moveRowAt:to:)](https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614867-tableview) UITableViewDataSource won’t be called for handling drops if the above methods are implemented. [tableView(_:performDropWith:)](https://developer.apple.com/documentation/uikit/uitableviewdropdelegate/2897427-tableview) UITableViewDataSource , reordering is handled in the same manner as copying. The only difference is — you were inserting a brand new item at the destination index path, but you need to delete an item from source index path and insert it at the destination index path. In collection views in copying in reordering The logic is changed a bit, rest everything remains same. the obtained from in 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 runtime error. Note: destinationIndexPath coordinator collectionView(_:performDropWith:) Array index out of bounds Oh Wait ! I have , but from where do I get ? destinationIndexPath sourceIndexPath Well, we have an answer for that too. can be obtained corresponding to each item fetched using . If the item is originated from the same collection view, this property contains the item’s original index path. [sourceIndexPath](https://developer.apple.com/documentation/uikit/uicollectionviewdropitem/2897392-sourceindexpath) coordinator 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. We can control the reordering speed for a better user experience using of type on collection view object. reorderingCadence enum UICollectionViewReorderingCadence can have these possible values: reorderingCadence — Items are reordered into place immediately. ( ) immediate default value — Items are reordered quickly, but with a short delay. fast — Items are reordered after a delay. slow Set the appropriate value of on your collection view object in . reorderingCadence viewDidLoad() 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. — A set of parameters for adjusting the appearance of a drag item preview. UIDragPreviewParameters 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 if you implement it. nil To customize the drag preview, implement method of . [collectionView(_:dragPreviewParametersForItemAt:)](https://developer.apple.com/documentation/uikit/uicollectionviewdragdelegate/2897459-collectionview) 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 !! Sample Project You can download the sample project from . here Promotions 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.