Search code examples
iosswiftuicollectionviewios9

UICollectionViewController reordering does not work when embedded in a container view


Reordering is working in iOS9 when I add this to my UICollectionViewController subclass

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

It does not work when this UICollectionViewController 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?


Solution

  • 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)
        {
    
        switch(gesture.state)
        {
    
        case UIGestureRecognizerState.Began:
            guard let selectedIndexPath = self.collectionView!.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else
            {
                break
            }
            collectionView!.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)
        case UIGestureRecognizerState.Changed:
            collectionView!.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!))
        case UIGestureRecognizerState.Ended:
            collectionView!.endInteractiveMovement()
        default:
            collectionView!.cancelInteractiveMovement()
        }
    }
    

    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.