Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 8 UICollectionViewLayout Switching Mysterious Crash in Swift

I am new working with UICollectionView. I am trying to switch UICollectionViewLayout from grid to list and vice versa using the below code:

@IBAction func switchLayout(sender: AnyObject) {
    isGridLayout = !isGridLayout

    collectionView?.reloadData()

    if isGridLayout {            

        collectionView?.performBatchUpdates({ () -> Void in
            self.collectionView?.collectionViewLayout.invalidateLayout()
            self.collectionView?.setCollectionViewLayout(self.gridLayout, animated: true)
            }, completion: { (completion) -> Void in
        })

    } else {            

        collectionView?.performBatchUpdates({ () -> Void in
            self.collectionView?.collectionViewLayout.invalidateLayout()
            self.collectionView?.setCollectionViewLayout(self.listLayout, animated: true)
            }, completion: { (completion) -> Void in
        })            
    }
}

I consistently get the below crash on setCollectionViewLayout:animated: method, which I don't understand. Any help on fixing this crash would be great!

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: <NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0})'

The project is available in github. Its a modified form of this tutorial.

like image 837
Dhanush Balachandran Avatar asked Nov 01 '22 04:11

Dhanush Balachandran


1 Answers

Because you set the headerReferenceSize in your FlowLayout. It means that the collectionView will have a Supplementary View.

So comment out the code of headerReferenceSize or implement the collectionView(_:viewForSupplementaryElementOfKind:at:) in your ViewController.

like image 64
Zachary Zhang Avatar answered Nov 03 '22 01:11

Zachary Zhang