Disable Rotation of UIViewController Embedded Into UINavigationController

In this short Swift code example, you will learn how to disable rotation of the UIViewController which is embedded into UINavigationController.

  • We will need to override the shouldAutorotate function and return a value of false,
  • Add to current UIViewController a UINavigationController extension.

Disable Rotation of UIViewController Complete Code Example in Swift

Below is a very simple example of UIViewController that demonstrates how you can disable its rotation. Try running this example in your Xcode project. See how it works.

import UIKit
class ViewController: UIViewController  {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override open var shouldAutorotate: Bool {
        return false
    }
    
}
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
        }
    }
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published.