UICollectionView - resizing cells on device rotate - Swift
Perhaps the most straight way to make this is to invalidateLayout during the viewWillTransitionToSize:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
flowLayout.invalidateLayout()
}
To have the collection view resize its cells, and have the change animated during rotation, use the transition coordinator:
(Swift 4+)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Have the collection view re-layout its cells.
coordinator.animate(
alongsideTransition: { _ in self.collectionView.collectionViewLayout.invalidateLayout() },
completion: { _ in }
)
}