iosswiftuiinterfaceorientation

Swift: Enable landscape for one controller and for the rest only portrait


My application was only in portrait mode, but I need a controller to also support landscape.

Here my info.plist:

    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>

And in my app delegate I have added this:

var shouldRotate = false

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return shouldRotate ? .allButUpsideDown : .portrait
    }

In my controller:

    override func viewDidLoad() {
        super.viewDidLoad()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.shouldRotate = true // or false to disable rotation
    }

But the controller not rotate, what is my mistake? This controller is open in modal on a navigation controller


Solution

  • Past in controlllers seprately, According to your requirment.

    override public var shouldAutorotate: Bool {
        return true
    } 
    
    override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .all
    }
    
    override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .all
    }
    

    this should be in viewcontroller, where you want both landscape and portrait.

    // other Viewcontrollers :

    override public var shouldAutorotate: Bool { return false }

    override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    

    // add this in viewcontroller ehere you want Application in portrait oreintation.

    Enable all required orientation for whole Application.

    And please remove your code in appDelegate related to orientation