This is a common question on StackOverflow, but none of the other solutions worked. Many were also written several years ago.
Here are some of the posts considered:
Is it possible to have different orientations for viewControllers inside UINavigationController?
Support landscape for only one view in UINavigationController
Is it possible to have different orientations for viewControllers inside UINavigationController?
Why can't I force landscape orientation when use UINavigationController?
How to force view controller orientation in iOS 8?
We have several view controllers embedded inside a UINavigationController: A, B, C, D.
A, B use portrait.
C, D use landscape.
A is the root controller.
Assume B gets pushed onto A. That works since B is portrait. However, when C gets pushed onto B, the screen doesn't rotate since as the class docs state:
Typically, the system calls this method only on the root view controller of the window or a view controller presented to fill the entire screen; child view controllers use the portion of the window provided for them by their parent view controller and no longer participate directly in decisions about what rotations are supported.
So overriding supportedInterfaceOrientations
inside a custom UINavigationController doesn't help because it isn't consulted on transitions within embedded controllers.
Effectively, we need a way to force orientation changes upon transitions, but there seems to be no supported method for this.
Here's how we override UINavigationController (extension is only used now for debugging purposes since apparently extensions shouldn't be used for overriding):
extension UINavigationController {
override open var shouldAutorotate: Bool {
return true
}
override open var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return visibleViewController?.supportedInterfaceOrientations ?? UIInterfaceOrientationMask.landscapeRight
}
}
Within embedded view controllers, we try to set the orientation like this:
override var shouldAutorotate: Bool {
return true
}
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return UIInterfaceOrientation.landscapeRight
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscapeRight
}
To summarize, the goals are:
1) Show view controllers embedded inside a UINavigationController with different orientations.
2) VC transitions should yield proper orientation change (e.g., popping from C->B should yield portrait, popping from D->C should yield landscape, pushing from B->C should yield landscape, pushing from A->B should yield portrait).
If it were possible to force the UINavigationController into an orientation (with publicly supported method), one possible solution could be to force the orientation upon showing the new view controller. But this also doesn't seem possible.
Suggestions?