我有一个应用程序,我只在其目标设置中将方向设置为纵向:
在一个特定的视图控制器中,我想覆盖此设置,以便自动布局在设备旋转时更新视图。我尝试过这些方法没有成功:
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.AllButUpsideDown
}
答案 0 :(得分:4)
您所需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中,你可以在didLoad和。上调用setAutoRotation(true) willDissapear上的setAutoRotation(false)。
这也可以通过继承UINavigationController来实现。你可以找到答案here。 希望它有所帮助
答案 1 :(得分:3)
如果我已经阅读了接受的答案,我就不必写自己的答案了。我的版本较长,但只需要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可能会被忽略。但是,我没有验证。
Swift 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]
}