Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to lock portrait orientation for only main view using swift

Tags:

ios

swift

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 view to Portrait orientation and only a subview of a navigation controller locked in Landscape orientation. Here is an example of what i mean:

  • UINavigationController
    • UiViewController1 (Locked in Portrait) Initial view controller with a button placed on the navigation bar that give to the user the possibility to access to a lists where can be selected other views
    • UIViewController2 (Locked in Landscape)
    • UiViewController3 (Portrait and Landscape)
    • UiViewController4 (Portrait and Landscape)
    • ...
    • ...

How Can i do that?

like image 920
Mono.WTF Avatar asked Sep 01 '14 12:09

Mono.WTF


People also ask

How do I lock my screen in portrait position?

If you don't want the screen to switch between portrait and landscape when you move the device, you can lock the screen orientation. To do this, swipe down from the right side of the top panel. Hold the device in the orientation in which you want it locked. On the drop-down menu, touch the “Auto Rotate” button.


1 Answers

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 :-)

like image 78
JasonJasonJason Avatar answered Oct 09 '22 07:10

JasonJasonJason