Swift 3
Rotation orientation is more complicated if the view controller is built into the UINavigationController or UITabBarController, the navigation controller or tab bar takes precedence and decides on autorotation and supported orientation.
Use the following extensions in the UINavigationController and UITabBarController so that the view controllers built into one of these controllers make decisions:
UINavigationController Extension
extension UINavigationController { override open var shouldAutorotate: Bool { get { if let visibleVC = visibleViewController { return visibleVC.shouldAutorotate } return super.shouldAutorotate } } override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ get { if let visibleVC = visibleViewController { return visibleVC.preferredInterfaceOrientationForPresentation } return super.preferredInterfaceOrientationForPresentation } } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{ get { if let visibleVC = visibleViewController { return visibleVC.supportedInterfaceOrientations } return super.supportedInterfaceOrientations } }}
UITabBarController Extension
extension UITabBarController { override open var shouldAutorotate: Bool { get { if let selectedVC = selectedViewController{ return selectedVC.shouldAutorotate } return super.shouldAutorotate } } override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ get { if let selectedVC = selectedViewController{ return selectedVC.preferredInterfaceOrientationForPresentation } return super.preferredInterfaceOrientationForPresentation } } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{ get { if let selectedVC = selectedViewController{ return selectedVC.supportedInterfaceOrientations } return super.supportedInterfaceOrientations } }}
Now you can override the supported InterfaceOrientations, shouldAutoRotate and preferredInterfaceOrientationForPresentation in the view controller that you want to block, otherwise you can leave the overrides in other view controllers that you want to inherit by default for the orientation specified in your application.
Orientation Lock
class YourViewController: UIViewController { open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{ get { return .portrait } }}
Disable rotation
class YourViewController: UIViewController { open override var shouldAutorotate: Bool { get { return false } }}
Change preferred presentation orientation for presentation
class YourViewController: UIViewController { open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ get { return .portrait } }}
Dragos Sep 24 '16 at 9:11 2016-09-24 09:11
source share