Search code examples
iosorientationswiftuilandscapeportrait

SwiftUI Force Portrait On All Except One View


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?


Solution

  • 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.rawValue, forKey: "orientation")
    UIViewController.attemptRotationToDeviceOrientation()
    

    And on dismissal,

    AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
    UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
    UIViewController.attemptRotationToDeviceOrientation()
    

    Hope this helps!