有时,当您使用自定义导航流程(可能会变得非常复杂)时,上述解决方案可能并不总是有效。此外,如果您有多个 ViewController 需要支持多个方向,这可能会变得非常乏味。
这是我找到的一个相当快速的解决方案。定义一个类 OrientationManager 并使用它来更新 AppDelegate 中支持的方向:
class OrientationManager {
static var landscapeSupported: Bool = false
}
然后在 AppDelegate 中为特定情况输入您想要的方向:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if OrientationManager.landscapeSupported {
return .allButUpsideDown
}
return .portrait
}
然后在您想要多个导航的 ViewControllers 中更新 OrientationManager:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
OrientationManager.landscapeSupported = true
}
另外,当你要退出这个 ViewController 时不要忘记再次更新它:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
OrientationManager.landscapeSupported = false
//The code below will automatically rotate your device's orientation when you exit this ViewController
let orientationValue = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(orientationValue, forKey: "orientation")
}
希望这会有所帮助!
更新:
您可能只想将static func 添加到您的Orientation Support Manager 类中:
static func setOrientation(_ orientation: UIInterfaceOrientation) {
let orientationValue = orientation.rawValue
UIDevice.current.setValue(orientationValue, forKey: "orientation")
landscapeSupported = orientation.isLandscape
}
然后,您可以在需要将方向设置回纵向时调用此函数。这也会更新静态的landscapeSupported 值:
OSM.setOrientation(.portrait)