Search code examples
iosswiftuiviewcontrolleruiinterfaceorientation

UIViewController changes orientation while told not to do so


I have a UIViewController where I override those 2 methods:

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait
}

override func shouldAutorotate() -> Bool {
    return false
}

My device orientation is ticked for Portrait, Landscape Left & Right.

I cleaned the build folder.

My problem: when I go to landscape, the app changes the orientation.

Any idea what's wrong. I thought overriding those two methods should be enough but it seems not.


Solution

  • Since your view controller is embedded in a UINavigationController and overridding shouldAutorotate() in the respective view controller alone wont work since it checks the shouldAutoRotate() of the UINavigationController/UITabBarController and therefore you will have to create a extension of UINavigationController

    extension UINavigationController {
        public override func shouldAutorotate() -> Bool {
            return visibleViewController.shouldAutorotate()
        }
    }
    

    And within the respective view controller wherever you want to lock the orientation as per your requirement override shouldAutoRotate()

    override func shouldAutorotate() -> Bool {
        return false
    }