How to Drag & Drop UICollectionView Cells by utilizing DropDelegate and DragDelegate

7th June 2019 Off By binary
How to Drag & Drop UICollectionView Cells by utilizing DropDelegate and DragDelegate
trading bonus no deposit

Drag, Drop & Reorder Collection View Cells into One or More UICollectionView

Think of an Instagram theme app where you can drag and drop your posts to create a clean feed before you post. If that doesn’t make sense, keep reading.

Swift is Protocol oriented, and yes, we love that.

Use the UICollectionViewDragDelegate and UICollectionViewDropDelegate Swift protocols in your apps to integrate drag and drop features.

Here is a gif of the app/functionality we will be building, along with the two protocols you will be learning how to use. If you’re here you are probably already familiar with UICollectionViewDelegateFlowLayout and UICollectionViewDataSource.

If you prefer a course format, check out my collection view course where we build this app and the Pinterest layout.

Step 1 — Setup a Collection View within a View Controller ✅

Step 1 & 2 I won’t explain because It’s basic collection view junk which isn’t the focus of this article. I WILL, however, explain the drop and drag protocols in-depth. Copy this code into your app to get a collectionView setup (you won’t see anything on the screen yet)

Class Naming

One thing to note is that I’ve named the class DragDrop. We will be using extensions on this class throughout the article.

Images

The items array is a collection of strings. These strings are our images. You can get high-quality images for free, here on unsplash.

Alexacea has really nice tech pics, which I use in every tutorial requiring images.

Step 2 — Utilize the DelegateFlowLayout and DataSource protocols to get some cells on the screen. ✅

Go ahead and copy the code pictured below into your application. Compile your code after you’ve done this.

We are ready.

Your app should look like this screenshot, without the UITabBar at the bottom, and large navigation title DragDrop. (Those are in here because they are a part of my collection course)

Step 3— Integrate UICollectionViewDragDelegate ✅

Type this code into your application, and uncomment collection.dragDelegate = self in your view did load.

Again! make sure you uncomment collection.dragDelegate = self in your view did load method. If you don’t, this code won’t do anything.

By creating an extension and adopting the UICollectionViewDragDelegate, we receive the god-like ability to drag cells in our collection views. (click the screenshot of my simulator on the right, you should be able to do this after completing this step. I’m simply dragging a cell, and it doesn’t do anything else yet.)

UICollectionViewDragDelegate

K but how is this happening? 🤷‍♂️

itemsForBeginning session is a method that requires us to return a collection of UIDragItem’s.

Which means, if we wanted to we could probably integrate a feature allowing the dragging of more than just one cell ¯_(ツ)_/¯.

It also begins a UIDragSession. For specifics check out the docs.

Step 4 — Handle a drop with UICollectionViewDropDelegate ✅

Copy this code into Xcode.

You’ll notice a warning and a commented line of code. Standby, I will explain in the next step.

Two methods

Listed here in the docs, with more unrequired methods.

dropSessionDidUpdate session

The first method returns a UICollectionViewDropProposal. This is how we tell the DropDelegate that something is happening when the user drags a cell and drops it at a new location.

performDropWith coordinator

The second method is where we put the code we want to run after the dropDelegate has been notified there will likely be a drop soon. All we are doing here is calculating whether or not the cell will be dropped out of bounds.

Hold up I’m VERY confused.

Hey, I was there too. So as soon as I finally comprehended it, I decided to make a course explaining each step for myself and others to reference.

Detect drops with UICollectionViewDropDelegate

Step 5 — Reordering data/items and Batch Updates on UICollectionView ✅

The last step is to implement the reorder items method. I’ve placed this method right below my view did load method, and marked it fileprivate as all good devs should do.

First, uncomment the line in the screenshot above. The line in the performDropWith method we’ve implemented.

This method requires three parameters.

  1. coordinator of type UICollectionViewDropCoordinator
  2. destinationIndexPath of type IndexPath
  3. collectionView of type UICollectionView

Why tho?

  1. On the last line, the coordinator object will allow us to tell the drop delegate we have performed a drop after we have modified our data. This allows for a smooth animation (the cell dropping in, not the collection view updating data)
  2. the destinationIndexPath is simply the destination at which we want our new cell to reside. It’s where we are dropping the cell.
  3. collectionView is obviously our collection view, we need this to perform batch updates, delete the dragged item from its original location, and insert it into the new location.

So go ahead, wrap the insertion and deletion of data & indexPaths in the performBatchUpdates method and watch the magic happen. Again, make sure you uncomment the line calling this method in our dropDelegate extension.

App Complete ✅

If you want to be the first to hear about limited FREE course coupons (10 per month) feel free to subscribe to my Weekly Dev Content Email List.

You now know how to;

  • use UICollectionView’s better
  • use UICollectionViewDragDelegate
  • use UICollectionViewDropDelegate
  • read, but mostly reference Apple documentation better
  • and hopefully, serendipitously you’ve learned a few other small things like how to use extensions if you haven’t yet used them

If you are still confused!!!!! 🙂 👨‍💻🧐

Two things you can do.

  1. Enroll in my UICollectionView course. I explain how to build this app from zero to complete, and the Pinterest layout! (The Pinterest layout is much more involved and I don’t even think I’d attempt writing an article on it.)
  2. save this article and keep referencing it until you comprehend it. This is exactly what I do with other concepts and medium articles. Not even kidding. I also want you to keep coming back to my content, no hidden schemes here…

More Resources — Advanced Guides. ✅

If this helped you, check out my YouTube videos to get a taste of how I do things on video.

If you like my videos, maybe you’ll like my highest rated course on iOS development.

Thank you so much for reading!

If you liked the article, please leave a clap and follow me on my social accounts. Every tweet, youtube subscription, medium clap, and Instagram comment helps me further help you with these articles and videos.

YouTube

Twitter

Thanks,

Max


How to Drag & Drop UICollectionView Cells by utilizing DropDelegate and DragDelegate was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

social trading binary options