UICollectionView - resizing cells on device rotate - Swift

后端 未结 9 1593
醉梦人生
醉梦人生 2020-12-04 23:12

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

9条回答
  •  我在风中等你
    2020-12-05 00:11

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

提交回复
热议问题