Silver Challenge: Updated Item Sizes

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() 
}

I just made PhotosViewController conform to UICollectionViewDelegateFlowLayout, then implemented the following method:

// MARK:- UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = self.collectionView.bounds.width / 4 - 8
    return CGSize(width: width, height: width)
}

Probably not very efficient as the method gets called for every cell, but it works.

As suggested by the challenge, I just did an override of the viewDidLayoutSubviews. I think it is probably the simplest solution:

override func viewDidLayoutSubviews() { // for the silver challenge
    
    guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
          return
    }

    let availableWidth = collectionView.bounds.inset(by: collectionView.layoutMargins).width
    let cellWidth = (availableWidth / 4).rounded(.down)
    layout.itemSize.width = cellWidth
    
}