How to force a UIViewController to Portrait orientation in iOS 6
Asked Answered
G

16

86

As the ShouldAutorotateToInterfaceOrientation is deprecated in iOS 6 and I used that to force a particular view to portrait only, what is the correct way to do this in iOS 6? This is only for one area of my app, all other views can rotate.

Greece answered 20/9, 2012 at 20:0 Comment(0)
R
117

If you want all of our navigation controllers to respect the top view controller you can use a category so you don't have to go through and change a bunch of class names.

@implementation UINavigationController (Rotation_IOS6)

-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

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

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}

@end

As a few of the comments point to, this is a quick fix to the problem. A better solution is subclass UINavigationController and put these methods there. A subclass also helps for supporting 6 and 7.

Ration answered 22/9, 2012 at 0:49 Comment(18)
I can confirm this works. You may also replace "[self.viewControllers lastObject]" with "self.topViewController" if you like.Batton
@aprato do I need to remove the old shouldAutorotateToInterfaceOrientation references from my code?Overburden
@Overburden If your app is only going to be iOS 6.0+, then yes, I would think you should. However, if you're going to support anything less than iOS 6.0, (5.1 and before), you should not change everything over yet as shouldAutorotate and supportedInterfaceOrientations are only iOS 6.0+.Skullcap
If you are using UITabBarController than this UINavigationController category is no help. You should make category on UITabBarController instead...Mesoderm
Problem with this solution is that it doesn't work when you pop controller that was in landscape and your new top controller supports only portrait (or vice versa), those callbacks are not called in this case and I am yet to find way how to force new top controller into correct orientation. Any ideas?Karnes
@Karnes have you made sure your nav controller is root to the key window? Which of the new rotation methods have you implemented?Ration
I subclassed UINavigationController and set it as window.rootController. I implemented all 3 methods, it works great when you change rotation of device, problem is that those methods (and nothing related to rotation) is called when you pop view controllerKarnes
@aparto could u please answer my question, I followed your answer for the current question during implementation. #13326301Mansized
@Karnes - Same exact issue here. Have you found anything? Supremely lame that Apple forces this design on every app imho.Gramineous
@Gramineous - sadly, I did not. I was forced to abandon landscape orientation and my apps now work only in portraitKarnes
I thought doing this myself, but seeing UIViewController defines those methods in categories itself, it should be safer to override them in subclasses. Also it does not cover the case when you push/pop/present a portrait only VC from a landscape one.Wald
If I am doing push or pop from landscape view controller then this force UIViewController changes into Landscape. However if I rotate into portrait then it works fine and it will never changed into landscape. The only problem while push or pop from landscape. Please helpScyros
@lope see my answer below regarding forcing portraitAliform
@toblepwn see my answer below regarding forcing portraitAliform
@BorutTomazin I have tabBarController having navigationControllers on each tab then What will be the solution? Any help will be appreciated.Subfloor
@Karnes Over three months later and still no fix for this. Anyone? Anyone??Maidel
@Lope, It has been a year now. Did you get a proper solution for this? I have the same issue.Lelalelah
@noundla I don't think I did, I change the design of the app so that I don't need it and then forgot about the issue. It's just not worth my nerves to work around questionable Apple's design decisionsKarnes
K
63

The best way for iOS6 specifically is noted in "iOS6 By Tutorials" by the Ray Wenderlich team - http://www.raywenderlich.com/ and is better than subclassing UINavigationController for most cases.

I'm using iOS6 with a storyboard that includes a UINavigationController set as the initial view controller.

//AppDelegate.m - this method is not available pre-iOS6 unfortunately

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
NSUInteger orientations = UIInterfaceOrientationMaskAllButUpsideDown;

if(self.window.rootViewController){
    UIViewController *presentedViewController = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
    orientations = [presentedViewController supportedInterfaceOrientations];
}

return orientations;
}

//MyViewController.m - return whatever orientations you want to support for each UIViewController

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
Kephart answered 21/12, 2012 at 0:12 Comment(9)
This is best solution for iOS 6Neoptolemus
@Phil, Its works fine for iOS 6. But in some cases, like if you go from landscape to portrait then it doesn't work. Any idea why it happens?Cly
Very usefull solution. For me, the best.Fushih
Working on iOS 7 beta 6. Works when going from landscape to portrait in my case.Kitty
I'm in iOS 6 but this doesn't work. It breaks on the "UIViewController *presentedViewController" line.Chirpy
I tried so many other solutions, but this is the only one that worked for me. It works great in iOS 6 & iOS 7 and was relatively easy to implement compared with other proposed solutions.Summand
This doesn't work for me. When rotating from portrait to landscape (or vice versa) on a viewController that only supports portrait, it 'locks' all the other viewControllers that support both portrait AND landscape.Maidel
This is the only solution I could get to work on IOS8Hitandrun
Simplest solution. Confirmed it works on iOS 9 with swift 2.0Chloris
A
39

This answer relates to the questions asked in the comments of the OP's post:

To force a view to appear in a given oriention put the following in viewWillAppear:

UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
    UIViewController *c = [[UIViewController alloc]init];
    [self presentModalViewController:c animated:NO];
    [self dismissModalViewControllerAnimated:NO];
}

It's a bit of a hack, but this forces the UIViewController to be presented in portrait even if the previous controller was landscape

UPDATE for iOS7

The methods above are now deprecated, so for iOS 7 use the following:

UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
     UIViewController *c = [[UIViewController alloc]init];
     [c.view setBackgroundColor:[UIColor redColor]];
     [self.navigationController presentViewController:c animated:NO completion:^{
            [self.navigationController dismissViewControllerAnimated:YES completion:^{
            }];
     }];
}

Interestingly, at the time of writing, either the present or dismiss must be animated. If neither are, then you will get a white screen. No idea why this makes it work, but it does! The visual effect is different depending on which is animated.

Aliform answered 24/2, 2013 at 22:39 Comment(9)
Thanks, I will give it a try when I find few minutes of free timeKarnes
@RohanAgarwal it does work as advertised, I'm using it here. But you need to have the accepted answer's code implemented as well, or it won't work.Papa
Has anyone figured out how to make this work with the correct rotation animation at the same time? It's a little jarring to see it switch from portrait to landscape without the animation. It works, just hoping to make it work a little better.Papa
@Craig Watkinson It is not working in storyboard. and presentModalViewController and dismissModalViewControllerAnimated is deprecated if iam using presentVirecontroller then it wont work .please help meBumboat
@Craig Watkinson Thanks for your great answer, working perfect!Oas
thanks it worked, dont know whats going to happen if apple change some thing in its api, have given around two days but can not solve problem of pushing a view in portrait from landscape in navigation based app.Knockabout
For ios8 dismissViewControllerAnimated just crashes. I found that calling [NWSAppDelegate sharedInstance].window.rootViewController = nil; [NWSAppDelegate sharedInstance].window.rootViewController = previousRootController works nice.Ginny
@Ginny Its not crashing in iOS8 for me.Periodate
@Craig Watkinson its working fine when i Push VC from landscap. but when i popview from landscap its crashing. Reason : 'preferredInterfaceOrientationForPresentation must return a supported interface orientation!' Please help me out on this.Abecedarium
C
36

So I ran into the same problem when displaying portrait only modal views. Normally, I'd create a UINavigationController, set the viewController as the rootViewController, then display the UINavigationController as a modal view. But with iOS 6, the viewController will now ask the navigationController for its supported interface orientations (which, by default, is now all for iPad and everything but upside down for iPhone).

Solution: I had to subclass UINavigationController and override the autorotation methods. Kind of lame.

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
// pre-iOS 6 support 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}
Carlyn answered 20/9, 2012 at 22:59 Comment(4)
doesn't work on mine. I had this code with global setted to all orientationsPremillennialism
supportedInterfaceOrientations should return an NSUInteger, not BOOL. See developer.apple.com/library/ios/#featuredarticles/…Beach
its worked, for me its the tabbarcontroller, again thanks for the answerHubby
FWIW, I had to go this route as well... Nothing else worked. Thanks.Sapper
K
16

IOS 5

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

IOS 6

-(BOOL)shouldAutorotate{
    return YES;
}

-(NSInteger)supportedInterfaceOrientations{

    //    UIInterfaceOrientationMaskLandscape;
    //    24
    //
    //    UIInterfaceOrientationMaskLandscapeLeft;
    //    16
    //
    //    UIInterfaceOrientationMaskLandscapeRight;
    //    8
    //
    //    UIInterfaceOrientationMaskPortrait;
    //    2

    //    return UIInterfaceOrientationMaskPortrait; 
    //    or
          return 2;
}
Kwangchowan answered 10/10, 2012 at 7:5 Comment(3)
Excellent! Need to be maximally at the top of this thread. Because it is the most simple way to solve problemJutland
@Roshan Jalgaonkar In ios 6 It does not work for me i need only portrait with down home button how can i set this UIOrientation....Calcification
@Calcification you have to enable supported rotations in your App's target for this to work.Millhon
W
10

I disagree from @aprato answer, because the UIViewController rotation methods are declared in categories themselves, thus resulting in undefined behavior if you override then in another category. Its safer to override them in a UINavigationController (or UITabBarController) subclass

Also, this does not cover the scenario where you push / present / pop from a Landscape view into a portrait only VC or vice-versa. To solve this tough issue (never addressed by Apple), you should:

In iOS <= 4 and iOS >= 6:

UIViewController *vc = [[UIViewController alloc]init];
[self presentModalViewController:vc animated:NO];
[self dismissModalViewControllerAnimated:NO];
[vc release];

In iOS 5:

UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *view = [window.subviews objectAtIndex:0];
[view removeFromSuperview];
[window addSubview:view];

These will REALLY force UIKit to re-evaluate all your shouldAutorotate , supportedInterfaceOrientations, etc.

Wald answered 21/1, 2013 at 19:34 Comment(4)
The first of these crashes for me regardless of iOS version. Says dismiss should not be called before present has finished.Leaseholder
@Leaseholder Can you post a snippet of how you're using it ? As long as it isn't animated it shouldn't have the issue you mentionWald
I also put the second snippet into viewDidAppear and it does nothing to help my situation on iOS 6. Question is here: #15654839Leaseholder
Sorry, one last comment here. Moving the iOS 5 code to viewDidAppear creates some sort of infinite loop with this output: -[UIApplication beginIgnoringInteractionEvents] overflow. Ignoring.Leaseholder
B
3

I have a very good approach mixing https://mcmap.net/q/162622/-how-to-force-a-uiviewcontroller-to-portrait-orientation-in-ios-6 and https://mcmap.net/q/107569/-how-to-find-topmost-view-controller-on-ios

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    NSUInteger orientations = UIInterfaceOrientationMaskAllButUpsideDown;


    if(self.window.rootViewController){
        UIViewController *presentedViewController = [self topViewControllerWithRootViewController:self.window.rootViewController];
        orientations = [presentedViewController supportedInterfaceOrientations];
    }

    return orientations;
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}

and return whatever orientations you want to support for each UIViewController

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
Bonner answered 5/9, 2013 at 12:33 Comment(0)
E
1

Not to be dull here, but would you be so kind to share your subclass? Thank you.

edit: well, I finally did it, the subclass was dead simple to do. I just had to declare the navigationController in the AppDelegate as UINavigationControllerSubclass instead of the default UINavigationController, then modified your subclass with:

- (BOOL)shouldAutorotate {
    return _shouldRotate;
}

so I can set any view I want to rotate or not by calling at viewDidLoad

_navController = (UINavigationController *)self.navigationController;
[_navController setShouldRotate : YES / NO]

Hope this tweak will help others as well, thanks for your tip!

Tip: Make use of

- (NSUInteger)supportedInterfaceOrientations

in your view controllers, so you don't end up by having a portrait desired view in landscape or vice versa.

Evincive answered 20/9, 2012 at 23:59 Comment(0)
D
1

I have a relatively complex universal app using UISplitViewController and UISegmentedController, and have a few views that must be presented in Landscape using presentViewController. Using the methods suggested above, I was able to get iPhone ios 5 & 6 to work acceptably, but for some reason the iPad simply refused to present as Landscape. Finally, I found a simple solution (implemented after hours of reading and trial and error) that works for both devices and ios 5 & 6.

Step 1) On the controller, specify the required orientation (more or less as noted above)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

-(BOOL)shouldAutorotate
{
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    NSInteger mask = UIInterfaceOrientationMaskLandscape;
    return mask;

}

Step 2) Create a simple UINavigationController subclass and implement the following methods

-(BOOL)shouldAutorotate {
        return YES;
}
- (NSUInteger)supportedInterfaceOrientations {
        return UIInterfaceOrientationMaskLandscape;
}

Step 3) Present your viewController

vc = [[MyViewController alloc]init];
MyLandscapeNavigationController *myNavigationController = [[MyLandscapeNavigationController alloc] initWithRootViewController:vc];
[self myNavigationController animated:YES completion:nil];

Hope this is helpful to someone.

Dollhouse answered 9/2, 2013 at 12:49 Comment(0)
F
0

I did not test it myself, but the documentation states that you can now override those methods: supportedInterfaceOrientations and preferredInterfaceOrientationForPresentation.

You can probably achieve what you want y setting only the orientation that you want in those methods.

Foretopgallant answered 20/9, 2012 at 20:26 Comment(0)
C
0

The answers using subclasses or categories to allow VCs within UINavigationController and UITabBarController classes work well. Launching a portrait-only modal from a landscape tab bar controller failed. If you need to do this, then use the trick of displaying and hiding a non-animated modal view, but do it in the viewDidAppear method. It didn't work for me in viewDidLoad or viewWillAppear.

Apart from that, the solutions above work fine.

Crossroad answered 14/6, 2013 at 11:38 Comment(0)
C
0

For Monotouch you could do it this way:

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
    {
    return UIInterfaceOrientationMask.LandscapeRight;
}

public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation()
    {
    return UIInterfaceOrientation.LandscapeRight;
}
Copenhagen answered 12/7, 2013 at 20:44 Comment(0)
P
0

I see the many answer but not get the particular idea and answer about the orientation but see the link good understand the orientation and remove the forcefully rotation for ios6.

http://www.disalvotech.com/blog/app-development/iphone/ios-6-rotation-solution/

I think it is help full.

Phocomelia answered 13/9, 2013 at 6:30 Comment(0)
P
-1

Just go to project.plist then add Supported interface orientation and then add only Portrait (bottom home button) and Portrait (top home button).

You can add or remove there orientation as per your project requirement .

Thanks

Passably answered 13/1, 2013 at 10:15 Comment(1)
its about particular view controller not for whole application.Anchoveta
C
-2

1) Check your project settings and info.plist and make sure that only the orientations you want are selected.

2) add the following methods to your topmost view controller(navigation controller/tabbar controller)

- (NSUInteger) supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;

}

3) add the following methods to your app delegate

- (NSUInteger) supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;

}

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;

}
Casilde answered 9/1, 2013 at 8:17 Comment(0)
C
-3

Put this in the .m file of each ViewController you don't want to rotate:

- (NSUInteger)supportedInterfaceOrientations
{
    //return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft;
    return UIInterfaceOrientationMaskPortrait;
}

See here for more information.

Cantata answered 23/6, 2013 at 21:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.