Swift - How to detect orientation changes

后端 未结 13 1794
余生分开走
余生分开走 2020-11-29 19:49

I want to add two images to single image view (i.e for landscape one image and for portrait another image)but i don\'t know how to detect orientation changes using swift lan

13条回答
  •  执笔经年
    2020-11-29 20:42

    To get the correct orientation on app start you have to check it in viewDidLayoutSubviews(). Other methods described here won't work.

    Here's an example how to do it:

    var mFirstStart = true
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if (mFirstStart) {
            mFirstStart = false
            detectOrientation()
        }
    }
    
    func detectOrientation() {
        if UIDevice.current.orientation.isLandscape {
            print("Landscape")
            // do your stuff here for landscape
        } else {
            print("Portrait")
            // do your stuff here for portrait
        }
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        detectOrientation()
    }
    

    This will work always, on app first start, and if rotating while the app is running.

提交回复
热议问题