How to lock orientation of one view controller to portrait mode only in Swift

后端 未结 16 2203
梦谈多话
梦谈多话 2020-11-22 12:07

Since my app got support for all orientation. I would like to lock only portrait mode to specific UIViewController.

e.g. assume it was Tabbed Application and when Si

16条回答
  •  萌比男神i
    2020-11-22 12:26

    Swift 3 & 4

    Set the supportedInterfaceOrientations property of specific UIViewControllers like this:

    class MyViewController: UIViewController {
    
        var orientations = UIInterfaceOrientationMask.portrait //or what orientation you want
        override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
        get { return self.orientations }
        set { self.orientations = newValue }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        //...
    }
    

    UPDATE

    This solution only works when your viewController is not embedded in UINavigationController, because the orientation inherits from parent viewController.
    For this case, you can create a subclass of UINavigationViewController and set these properties on it.

提交回复
热议问题