James Zaghini James Zaghini - 1 year ago 108
iOS Question

UICollectionViewController reordering does not work when embedded in a container view

Reordering is working in iOS9 when I add this to my


override func collectionView(collectionView: UICollectionView,
moveItemAtIndexPath sourceIndexPath: NSIndexPath,
toIndexPath destinationIndexPath: NSIndexPath)

It does not work when this
subclass is embedded in a container view.

I've made a demo of the problem here

Any ideas on why or how to fix it?

Answer Source

The issue here is that you put the UICollectionView inside a UIContainerView that is residing inside a UIViewController. This requires just a few more steps for the UICollectionView to work as expected.

Add the following to ViewDidLoad in your CollectionViewController:

    self.collectionView!.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "handleLongGesture:"))

Then add the following function to your CollectionViewController:

    func handleLongGesture(gesture: UILongPressGestureRecognizer)


    case UIGestureRecognizerState.Began:
        guard let selectedIndexPath = self.collectionView!.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else
    case UIGestureRecognizerState.Changed:
    case UIGestureRecognizerState.Ended:

Finally just make sure to include the following to ensure you handle the dataSource correctly:

    override func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath,toIndexPath destinationIndexPath: NSIndexPath) {
    // Swap the values of the source and destination

Check out this link for more on this.

Hope this helped you out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download