Slavcho Slavcho - 25 days ago 15
Swift Question

Lock only one ViewController's orientation to landscape, and the remaining to portrait

I want to lock orientation in all ViewControllers to portrait, except on one of them, when it is pushed always to be in landscapeRight.
I've tried many solutions, using extensions for

UINavigationController
, overriding
supportedInterfaceOrientations
and
shouldAutorotate
but no luck.

Answer

I've found the solution, which for now it is working.

  1. On every view controller you should put this code for supporting only the desired rotation (landscapeRight in the example):

    override var shouldAutorotate: Bool { return true }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.landscapeRight
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .landscapeRight
    }
    

    On the other implement the same methods but with portrait orientation.

  2. Create an extension for UINavigationController

    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return (self.topViewController?.supportedInterfaceOrientations)!
    }
    
    open override var shouldAutorotate: Bool {
        return true
    }
    

Note: Also in Project's target enable all desired supported orientations.

The only one controller that I wanted to show in landscape mode i presented modally.