UICollectionView and Dynamically changing Layouts on Runtime

So you’ve been trying to set custom layouts on run time on a UICollectionView or you were trying to change the UICollectionView’s cell count per row. But you’ve realised that it eventually crashes instead of getting what you want done. It’s mainly because you need to invalidate your UICollectionView’s layout. It can be simply done by calling the line below in Swift 3.

self.collectionView.collectionViewLayout.invalidateLayout()

But you should also be careful where you are calling this function. Ideally you should call it after reloading data in the UICollectionView.

For example something like below

self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()

Originally written at jaymayu.com