I\'ve created a UICollectionView, so that I can arrange views into neat columns. I\'d like there to be a single column on devices > 500 pixels wide.
In order to achi
I have used following approach, which worked for me. Problem with me was that I was invalidating layout in
viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
But at this point (as this method name suggest) Device has not been rotated yet.
So this method will be called before viewWillLayoutSubviews and hence in this method we do not have right bounds and frames (Safe Area) as device will rotate afterwards.
So I used notifications
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}
@objc func rotated(){
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
flowLayout.invalidateLayout()
}
and then in collection view flow delegate method everything works as expected.
extension ViewController: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
if #available(iOS 11.0, *) {
return CGSize(width: view.safeAreaLayoutGuide.layoutFrame.width, height: 70)
} else {
return CGSize(width: view.frame.width, height: 70)
}
}
}