How to support drag and drop in UICollectionView iOS

Issue #411

See DragAndDrop example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class ViewController: UIViewController, UICollectionViewDropDelegate, UICollectionViewDragDelegate {

// MARK: - UICollectionViewDragDelegate

func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let controller = leftController

let provider = NSItemProvider(
object: controller.imageForCell(indexPath: indexPath)
)

let dragItem = UIDragItem(itemProvider: provider)
dragItem.localObject = indexPath
return [dragItem]
}

// MARK: - UICollectionViewDropDelegate

func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {

let destinationIndexPath: IndexPath
if let indexPath = coordinator.destinationIndexPath {
destinationIndexPath = indexPath
} else {
destinationIndexPath = IndexPath(row: 0, section: 0)
}

let controller = rightController

let dragItemIndexPath = coordinator.items.last?.dragItem.localObject as! IndexPath
let draggedItem = leftController.items[dragItemIndexPath.item]

// remove
leftController.items.remove(at: dragItemIndexPath.item)
leftController.collectionView.deleteItems(at: [dragItemIndexPath])

// insert
controller.items.insert(draggedItem, at: destinationIndexPath.item)
controller.collectionView.insertItems(at: [destinationIndexPath])
}
}

Comments