cannot get shouldautorotate to fire when changing orientation

1.6k Views Asked by At

I'm developing an app with Xcode9 using Swift4 and it was originally intended for just iPads but now needs to run on phones too. I need to lock the phones to Portrait and iPads remain Portrait/Landscape.

I've done this before using the shouldautorotate function and returning true or false depending on the device as below.

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

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

However, when I change the orientation it does not fire. Is this another depreciated method and if so how do I restrict the orientation now?

2

There are 2 best solutions below

0
user616076 On BEST ANSWER

After much googling, this worked for me

https://stackoverflow.com/questions/38969419/ios-how-can-enable-or-disable-rotate-on-each-uiviewcontroller
1
Modo Ltunzher On

If your view controller is embedded into UINavigationController or UITabBarController, then this shouldAutorotate() is queried from them as this container is the topmost view controller. And after iOS updates it does not ask for contaning view controllers if they need to be rotated or not. Thus you may use your custom subclass and creat it in runtime or provide as custom calss in your storyboard:

import UIKit
class CustomNavigationController: UINavigationController {
    override var shouldAutorotate: Bool {
        return self.viewControllers.last?.shouldAutorotate ?? true
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return self.viewControllers.last?.supportedInterfaceOrientations ?? .all
    }        
}