I made a simple test app with the following code in my view controller:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
print("view will transition to \(size)")
}
Here is the output from using split view on an iPad:
view will transition to (694.0, 768.0)
view will transition to (507.0, 768.0)
view will transition to (1024.0, 768.0)
1. Enabled split view to 2/3 of screen
2. Changed split view to 1/2 of screen
3. Disabled split view (to full screen)
From this test, I showed that viewWillTransition(to:with:) is called every time split view is enabled, changed, or disabled.
The first code snippet that you posted seems OK. (Though I did forget to mention that super should be called — line 4.)
// In your view controller:
// This method is called when the app screen size changes.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
// Adjust the layout. This is a flow layout example.
// flowLayout.minimumInteritemSpacing = size.width / 0.0
// flowLayout.itemSize = CGSize(width: size.width / 0.0, height: 0.0)
// Invalidate the layout.
flowLayout.invalidateLayout()
}
collectionView?.reloadData()
}
So, if you are still having problems, there might be a problem with your layout code. For example, I would use UITraitCollection instead of UIDevice.current.orientation. Put some print statements in different places so you can check to see what is/what isn't being called when the collection view is reloaded.