Robert Robert -4 years ago 127
iOS Question

Prevent autorotate for one view controller?

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:

// ViewController.m

-(BOOL)shouldAutorotate
{
return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}


Can someone kindly point out what I'm doing wrong? Thanks.

-edit-

It's for iOS 6.1

Answer Source

When a UINavigationController is involved, create a category on the UINavigationController and override supportedInterfaceOrientations.

 #import "UINavigationController+Orientation.h"

 @implementation UINavigationController (Orientation)

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

-(BOOL)shouldAutorotate
 {
    return YES;
 }

@end  

Now, iOS containers (such as UINavigationController) do not consult their children to determine whether they should autorotate.

How to create a category
1. Add a new file (Objective c- category under cocoa touch)
2. Category : Orientation on UINavigationController
3. Add the above code to UINavigationController+Orientation.m

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download