In my App all Views are forced to portrait orientation via info.plist.
The exception should be "MyView" which should always be in landscape orientation.
What I did after taking a deeper look in SO:
Added in AppDelegate.swift:
static var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppDelegate.orientationLock
}
MyView.swift
struct MyView: View {
var body: some View {
ZStack {
// ...Some Images, etc.
}
.onAppear(perform: orientationLandscape)
.onDisappear(perform: orientationPortrait)
}
func orientationLandscape() {
AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeRight
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
}
func orientationPortrait() {
AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
UIDevice.current.setValue(UIInterfaceOrientation.portrait, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()
}
}
UIDevice.current.setValue produces an error. Without that line I can change the orientation in MyView manually by holding the device in landscape/portrait but it should switch automatically when opening and closing the View.
I solved this by orientating on bmjohns answer on a similar question: