UICollectionView Cell drag and drop Swift 4

Опубликовано: 23 Май 2026
на канале: Divyesh Gondaliya
6,912
85

In this tutorial, I will cover how to reorder cells in UICollectionView using drag & drop. I have seen many different approaches on how to do this, some are working decent and some are not. That's why I will show you the approach that is tested and working hundred percent.

To make this tutorial shorter, I will only present how to do the reordering and won't show all the required delegate methods. Since you got here, I count that you already know the UICollectionView basics.

Collectionview inside ScrollView :-    • Collectionview inside Scrollview  
Dynamic height TableView in a Scroll View :-    • Dynamic height TableView in a Scroll View  

Note: This tutorial has been updated (11/08/2018)to use Xcode 9.4.1 and Swift 4.
PLEASE DON'T FORGET TO SUBSCRIBE MY CHANNEL TO STAY UPDATED WITH NEW TRENDS!

  / iosinfoandknowledge  

My Social Media link is below
-------------
instagram :-   / gdivyesh40  
facebook :- https://www.facebook.com/profile.php?...


/////////////---------_Code_---------///////////////////
1 Enable the use of moving items in the UICollectionView by calling canMoveItemAt delegate method. Passing true will enable this feature.

func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -|gt| Bool {
return true
}

2 Next, we will implement the moveItemAt delegate method where you will intercept the starting index and the ending index of the both items that are switching places.
import UIKit

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = str_arr.remove(at: sourceIndexPath.item)
str_arr.insert(item, at: destinationIndexPath.item)
print(str_arr)
}

3 UILongPressGestureRecognizer, For a better control of the gestures in the UICollectionView we will implement a UILongPressGestureRecognizer.

fileprivate var longPressGesture: UILongPressGestureRecognizer!
@IBOutlet weak var collectionview: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
collectionview.addGestureRecognizer(longPressGesture)

}


@objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {

case .began:
guard let selectedIndexPath = collectionview.indexPathForItem(at: gesture.location(in: collectionview)) else {
break
}
collectionview.beginInteractiveMovementForItem(at: selectedIndexPath)
case .changed:
collectionview.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case .ended:
collectionview.endInteractiveMovement()
default:
collectionview.cancelInteractiveMovement()
}
}