Forcing screen orientation for a VC

This is an often asked question, but I just have a partial answer so far.

There are some views (not all) that I need to present in Portrait only when running on iPhone.

If I come from a TabBar, I just add the following code in the TabBar controller

    override open var supportedInterfaceOrientations : UIInterfaceOrientationMask     {
        
        if UIDevice.current.userInterfaceIdiom == .phone {
            return [.portrait, .portraitUpsideDown] 
        }
}

But I need to do the same when I get to the destination VC by a segue fired from a plain UIViewController or a Cell in a TableView.

If I put the code in the destination controller, it has no effect.

If I put in the originating VC, it works when segue is triggered from code (case 2 below).

But I cannot make it work when segue is triggered in storyboard from the accessory action in the cell of the TableView.

Where should I declare the supportedInterfaceOrientations ?

  • Should I do it in the navigation root ? If so, how ?
  • I tried in an extension UINavigationController, to no avail.
  • or should I trigger the segue from accessory, not directly in storyboard but through an IBAction in code ?

If that may help, an overview of storyboard setup:

Also tried solution described here to no avail either: https://www.appsdeveloperblog.com/disable-rotation-of-uiviewcontroller-embedded-into-uinavigationcontroller/

Answered by Claude31 in 777948022

Solution is really simple and obvious.

Subclass UINavigationController and set supportedInterfaceOrientations

class CustomNavController : UINavigationController {
    
    override open var supportedInterfaceOrientations : UIInterfaceOrientationMask     {
            return [.portrait, .portraitUpsideDown] 
    }
}

Change the class of NavigationRoot in storyboard to CustomNavController.

Accepted Answer

Solution is really simple and obvious.

Subclass UINavigationController and set supportedInterfaceOrientations

class CustomNavController : UINavigationController {
    
    override open var supportedInterfaceOrientations : UIInterfaceOrientationMask     {
            return [.portrait, .portraitUpsideDown] 
    }
}

Change the class of NavigationRoot in storyboard to CustomNavController.

Forcing screen orientation for a VC
 
 
Q