覆盖应用程序方向设置

我有一个应用程序,我只在其目标设置中将方向设置为纵向:

在此处输入图像描述

在一个特定的视图控制器中,我想覆盖此设置,因此自动布局将在旋转设备时更新视图。 我尝试过这些方法没有成功:

override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.AllButUpsideDown } 

您在所需VC中的代码将无法正常工作。 我通过在AppDelegate中添加以下代码来实现此目的

 var autoRotation: Bool = false func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask { return autoRotation ? .AllButUpsideDown : .Portrait } 

然后你可以创建一个帮助类并添加这个方法:

 class func setAutoRotation(value: Bool) { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.autoRotation = value } 

}

最后在你想要的VC中,你可以在didDoad上调用setAutoRotation(true),在willDissapear上调用setAutoRotation(false)。

这也可以通过inheritanceUINavigationController来实现。 你可以在这里找到答案。 希望能帮助到你

如果我已经阅读了接受的答案,我就不必自己写了。 我的版本更长,但只需要app delegate的application(_:supportedInterfaceOrientationsFor:)方法。 它可能适用于您无法更改或不想更改目标视图控制器的情况。 例如,第三方视图控制器。

我受到Apple官方文档的启发: supportedInterfaceOrientations

我的应用程序在iPhone上以肖像方式运行,在iPad上以所有方向运行。 我只想要一个视图控制器(一个JTSImageViewController呈现更大视图的图像)才能旋转。

的Info.plist

 Supported interface orientations = Portrait Supported interface orientations (iPad) = Portrait, PortraitUpsideDown, LandscapeLeft, LandscapeRight 

如果app delegate实现了application(_:supportedInterfaceOrientationsFor:) ,Info.plist可能会被忽略。 但是,我没有validation。

斯威夫特4

 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { // Early return for iPad if UIDevice.current.userInterfaceIdiom == .pad { return [.all] } // Search for the visible view controller var vc = window?.rootViewController // Dig through tab bar and navigation, regardless their order while (vc is UITabBarController) || (vc is UINavigationController) { if let c = vc as? UINavigationController { vc = c.topViewController } else if let c = vc as? UITabBarController { vc = c.selectedViewController } } // Look for model view controller while (vc?.presentedViewController) != nil { vc = vc!.presentedViewController } print("vc = " + (vc != nil ? String(describing: type(of: vc!)) : "nil")) // Final check if it's our target class. Also make sure it isn't exiting. // Otherwise, system will mistakenly rotate the presentingViewController. if (vc is JTSImageViewController) && !(vc!.isBeingDismissed) { return [.allButUpsideDown] } return [.portrait] }