iosswiftswiftuidevice-orientation

Force landscape orientation in one View


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.


Solution

  • I solved this by orientating on bmjohns answer on a similar question:

    1. Add some code in AppDelegate (this part i had already)
    2. Make a struct and func which does the job (small adjustments for XCode 11 and SwiftUI were needed)
    3. Execute the func onAppear of your View