implementing drag and drop in UICollectionView

by sisccr

I have a UICollectionView that displays the images in its cell. I need to allow user to re-order the images.One sleek way to achieve this is using drag and drop.

From Ios 9 and above, Using Drag and Drop feature is rather easy than I thought.

Let’s start:

First add a collectionView in the storyboard. My UICollectionView name is enterImageCollectionView

Add a custom cell for this CollectionView. My custom cell has just an ImageView inside it.

In ViewController, I implemented the protocol UICollectionViewDelegate and  UICollectionViewDataSource.

Screen Shot 2016-08-23 at 4.29.45 PM

 

 

First add a UILongPressGestureRecognizer to the collectionView.

create an  @IBAction for this  UILongPressGestureRecognizer.

@IBAction func longPressedEnterCollectionView(sender: UILongPressGestureRecognizer) {
        switch(sender.state) {
        case UIGestureRecognizerState.Began:
            guard let selectedIndexPath = enterImageCollectionView.indexPathForItemAtPoint(sender.locationInView(self.enterImageCollectionView)) else {
                break
            }
            enterImageCollectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)
        case UIGestureRecognizerState.Changed:
            enterImageCollectionView.updateInteractiveMovementTargetPosition(sender.locationInView(sender.view!))
        case UIGestureRecognizerState.Ended:
            enterImageCollectionView.endInteractiveMovement()
        default:
            enterImageCollectionView.cancelInteractiveMovement()
        }
    }

When user long press this gesture, the drag and drop feature begins.

When user drags the cell, gesture state is changed. And collectionView track the new position for the cell.

When user drops the cell, gesture state is ended. CollectionView ends the interactions.

We have a delegate function moveItemAtIndexPath for UICollectionView. Here we get the index of the element being removed and index where the removed element is to be placed.

 
extension MessageViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
        let element = enterImages.removeAtIndex(sourceIndexPath.row)
        enterImages.insert(element, atIndex: destinationIndexPath.row)
      }
    }

Here, enterImages is an array where number of images are saved.

Is that is?

Yes.  🙂

Advertisements