Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent autorotate for one view controller ios7?

Tags:

ios

rotation

ios7

My app can autorotate but I need one of the views to only show in portrait mode and don't know how to achieve this. I tried this (among other things) but the view in question still rotates:

-(BOOL)shouldAutorotate
{            
    return NO;
}

 - (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
like image 928
Victor Carreño Avatar asked Oct 26 '13 00:10

Victor Carreño


2 Answers

This solution explains how to control orientation on individual view controllers, provided they are managed by a navigation controller.

In Xcode 5, create a new file of type "Objective-C category", set it's "Category" to "rotation" and choose "UINavigationController" as "Category on".

A new file couple will appear in the project, having the following names: UINavigationController+rotation.h UINavigationController+rotation.m

In the .m file, write the following code:

- (BOOL) shouldAutorotate
{
    return [[self topViewController] shouldAutorotate];
}

- (NSUInteger) supportedInterfaceOrientations
{
    return [[self topViewController] supportedInterfaceOrientations];
}

This way, the navigation controller will let the current top view controller determine the orientation policy.

Then, in each specific view controller that is managed by the navigation controller, you can override the two orientation-related methods.

For instance, if a specific view controller shall appear in portrait orientation only:

- (BOOL) shouldAutorotate
{            
    return NO;
}

 - (NSUInteger) supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

Make sure that the desired orientation is one of those set in the project deployment info. Hope this is sufficiently detailed and can be of help.

like image 107
Giorgio Barchiesi Avatar answered Nov 06 '22 22:11

Giorgio Barchiesi


supportedInterfaceOrientations will work if you present your view controller as a modal view controller. It won't work if you present it as part of a navigation controller stack. If you want your view presented modally but inside a navigation controller (to have navigation items, for instance) the solution I did was to subclass UINavigationController and override the supportedInterfaceOrientations methods on my subclass.

like image 30
Simon Goldeen Avatar answered Nov 07 '22 00:11

Simon Goldeen