如果将视图控制器嵌入UINavigationController或UITabBarController中,则定向旋转会更加复杂,导航或选项卡栏控制器将具有优先权并就自动旋转和支持的定向做出决策。在UINavigationController和UITabBarController上使用以下扩展,以便嵌入在这些控制器之一中的视图控制器可以做出决定:UINavigationController扩展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 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 }}}现在,您可以在要锁定的视图控制器中重写supportedInterfaceOrientations,shouldAutoRotate和preferredInterfaceOrientationForPresentation,否则可以在其他视图控制器中忽略要继承应用程序plist中指定的默认方向行为的替代。锁定特定方向class YourViewController: UIViewController {open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{ get { return .portrait }}}禁用旋转 class YourViewController: UIViewController {open override var shouldAutorotate: Bool { get { return false }}}更改演示的首选界面方向class YourViewController: UIViewController {open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ get { return .portrait }}}