According to multiple SO questions and answers, the right way of updating the layout of UICollectionView is to call invaliditateLayout()
from within the UICollectionViewController's viewDidLayoutSubviews()
. In my case, however, this causes an infinite loop, because after invalidating the layout, viewDidLayoutSubviews()
gets called again etc.
Is it an artifact of some error I made somewhere, and so do I need to fix it? What could be the cause? Or is there any other new recommended way on how to invalidate layout?
Per request, here is the SO thread/answer I was referring to.
Per another request, the relevant piece of code follows. I set the size of the collection view with autolayout, and want to show exactly one item at once in the collection view, so I need to dynamically set its size after autolayout finishes. I do that using flow layout delegate.
// In ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout
// necessary to prevent loop
var shouldLayout = true
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let collectionView = collectionView else { return }
if shouldLayout {
collectionView.collectionViewLayout.invalidateLayout()
shouldLayout = false
}
}
// Later in the file
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
// Height and width to fit exactly one item into the CollectionView...
}