How to calculate iOS 11 size in different orientation?

前端 未结 2 1087
故里飘歌
故里飘歌 2021-02-13 09:16

I calculate itemSize dependent on safe area for UICollectionView with horizontal scroll and custom layout.

\"image\"

2条回答
  •  死守一世寂寞
    2021-02-13 09:45

    EDIT

    To get safe area size without creating any additional views, use this:

    view.safeAreaLayoutGuide.layoutFrame.size
    

    If you want to use viewWillTransition method you can use this:

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    
        // Before rotation
        print(view.safeAreaLayoutGuide.layoutFrame.size)
    
        coordinator.animate(alongsideTransition: { (context) in
            // During rotation
        }) { (context) in
            // After rotation
            print(self.view.safeAreaLayoutGuide.layoutFrame.size)
        }
    }
    

    In the completion block you will get your desired size, note however, that this code will be called after the rotation.

    Original answer

    Solution using additional UIView:

    What I did was to create a UIView and pin it with constant 0 to Safe Area Guides, so that it always matches size of Safe Area:

    I created an @IBOutlet of that UIView and in viewDidLayoutSubviews() check the size:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        print(containerView.frame.size)
    }
    

    After rotation I also get the updated size of that UIView.

提交回复
热议问题