This is a simple implementation of a drag and rearrange collection view through its layout. It works for UICollectionViews with multiple sections.
Video Demo: Here
Tip: For drag and drop between multiple collection views look at the project here.
-
Add the KDRearrangeableCollectionViewFlowLayout.swift file to your project (it is the only file you need).
-
Set the layout of your UICollectionView to be the one in the file above. This can be done either programmatically or through the Storyboard.
-
Make the data source of your UICollectionView to be KDRearrangeableCollectionViewDelegate subclass and implement the one mandatory method there.
func moveDataItem(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath) -> Void
An example implementation for a multisectioned UICollectionView is here:
func moveDataItem(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath) -> Void {
let name = self.data[fromIndexPath.section][fromIndexPath.item]
self.data[fromIndexPath.section].removeAtIndex(fromIndexPath.item)
self.data[toIndexPath.section].insert(name, atIndex: toIndexPath.item)
}
self.collectionViewRearrangeableLayout.draggable = true
self.collectionViewRearrangeableLayout.axis = .Free
self.collectionViewRearrangeableLayout.axis = .X
self.collectionViewRearrangeableLayout.axis = .Y
func canMoveItem(at indexPath : IndexPath) -> Bool
Another class that comes with this package is KDRearrangeableCollectionViewCell. It is a subclass of UICollectionViewCell and it implements a boolean property called 'dragging'. If you choose to make the cells of your collection view a subclass of KDRearrangeableCollectionViewCell this property will be set upon the start and end of the dragging and by overriding it you can set the style of the snapshot image that will be dragged around.
This method will be called before the visual swap happens.