Search code examples
ioslayoutuicollectionviewuinavigationcontroller

Invalidate layout of view controller that’s not visible


I have a UINavigationController with a UICollectionViewController as the first child view controller, which pushes another view controller onto the stack.

I call invalidateLatout() on the collection view layout when the device orientation changes, which resizes the cells. However it doesn’t work when I’ve navigated to the second view controller, presumably because the collection view isn’t visible.

I can see that invalidateLayout() is being called, but it doesn’t resize the cells when it’s not visible. Is there any way to force the view to layout in the background? (I’ve tried calling it in viewWillAppear() and using setNeedsLayout())


Solution

  • I was able to get it working by calling this in viewWillAppear()

    DispatchQueue.main.async {
        self.collectionViewLayout.invalidateLayout()
        self.collectionView.reloadData()
    }