问题
I have a SwiftUI project. For all but one of the views, I want to allow portrait and only portrait mode. For only one view, I want to allow both portrait and landscape. There are some resources on Swift but I couldn't find any on SwiftUI.
Did anyone find a way to accomplish this?
回答1:
I had to do something similar to this. Here's our approach.
We set the project orientation to only support Portrait mode.
Then in your AppDelegate
add an instance variable for orientation and conform to the supportedInterfaceOrientationsFor
delegate method.
static var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppDelegate.orientationLock
}
Then when your about to present your landscape view perform the following actions:
AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeLeft
UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
And on dismissal,
AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
UIDevice.current.setValue(UIInterfaceOrientation.portrait, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
Hope this helps!
来源:https://stackoverflow.com/questions/59633415/swiftui-force-portrait-on-all-except-one-view