I set mininum height : 90
I tested various simulator model.
I used NotificationCenter and detect orientationChanging.
Code
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() {
let perRow = 4
var cellWidth: CGFloat = 0.0
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
let availableWidth = collectionView.bounds.inset(by: collectionView.layoutMargins).width
if UIDevice.current.orientation.isLandscape {
cellWidth = (availableWidth / CGFloat(perRow)).rounded(.down)
}
else {
let maxNumColumns: CGFloat = CGFloat(round(availableWidth / 90))
cellWidth = (availableWidth / maxNumColumns).rounded(.down)
}
flowLayout.itemSize = CGSize(width: cellWidth, height: 90)
flowLayout.sectionInset = UIEdgeInsets(top: flowLayout.minimumInteritemSpacing, left: 0.0, bottom: 0.0, right: 0.0)
flowLayout.sectionInsetReference = .fromSafeArea
collectionView.collectionViewLayout = flowLayout
flowLayout.invalidateLayout()
}