how to lock portrait orientation for only main view using swift

后端 未结 16 1881
野性不改
野性不改 2020-12-07 13:38

I have created an application for iPhone, using swift, that is composed from many views embedded in a navigation controller. I would like to lock the main v

16条回答
  •  Happy的楠姐
    2020-12-07 14:05

    According to the Swift Apple Docs for supportedInterfaceOrientations:

    Discussion

    When the user changes the device orientation, the system calls this method on the root view controller or the topmost presented view controller that fills the window. If the view controller supports the new orientation, the window and view controller are rotated to the new orientation. This method is only called if the view controller's shouldAutorotate method returns true.

    Your navigation controller should override shouldAutorotate and supportedInterfaceOrientations as shown below. I did this in a UINavigationController extension for ease:

    extension UINavigationController {
        public override func shouldAutorotate() -> Bool {
            return true
        }
    
        public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
            return (visibleViewController?.supportedInterfaceOrientations())!
        }
    }
    

    And your main viewcontroller (portrait at all times), should have:

    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.Portrait
    }
    

    Then, in your subviewcontrollers that you want to support portrait or landscape:

    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.All
    }
    

    Edit: Updated for iOS 9 :-)

提交回复
热议问题