4

Is there any easy way to manually set the orientation of an interface? I need to set the interface to portrait even though the device orientation might be in landscape during loading. Kinda want to stay away from CGAffineTransforms.

brad_roush
  • 235
  • 1
  • 3
  • 10

3 Answers3

16

One method I know that works for me (and is a bit of a hack and can display one orientation before changing to the orientation you want) is:

- (void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];

    UIApplication* application = [UIApplication sharedApplication];

    if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
    {
        UIViewController *c = [[UIViewController alloc]init];
        [self presentModalViewController:c animated:NO];
        [self dismissModalViewControllerAnimated:NO];
        [c release];
    }
}
Shane Powell
  • 13,698
  • 2
  • 49
  • 61
  • This actually works really well for the situation I described. But for some reason does not work well with trying to force landscape from portrait mode(changing UIInterfaceOrientationPortrait to UIInterfaceOrientationLandscapeLeft). Ideas? – brad_roush Aug 31 '11 at 22:38
  • I have no idea Dan, you will have to try it yourself by making a sub-classed UIViewController that only handles landscape in the 'shouldAutorotateToInterfaceOrientation:' method. – Shane Powell Aug 08 '12 at 23:45
  • @ShanePowell, your code worked great on pre iOS6. Is there any such tricks for iOS6? – Ananth Sep 26 '12 at 08:36
2

override this to control the orientation until loading...

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
Saran
  • 6,274
  • 3
  • 39
  • 48
  • Yes, you are right. My mistake. I updated my answer. You can consider just overriding the shouldAutorotateToInterfaceOrientation and maintain the orientation as long as you need. – Saran Aug 31 '11 at 22:24
2

First, set your app and views to only support portrait, then use this category method taken from my refactoring library, es_ios_utils:

@interface UIViewController(ESUtils)
    // Forces without using a private api.
    -(void)forcePortrait;
@end

@implementation UIViewController(ESUtils)

-(void)forcePortrait
{
    //force portrait orientation without private methods.
    UIViewController *c = [[UIViewController alloc] init];
    [self presentModalViewController:c animated:NO];
    [self dismissModalViewControllerAnimated:NO];
    [c release];
}

@end

The view, dismissed before the frame completes, won't be displayed.

Peter DeWeese
  • 18,141
  • 8
  • 79
  • 101
  • I probably got this from Shane or whatever his source was. His is a bit more complete, and mine suggests the use of a category for reuse. – Peter DeWeese Aug 31 '11 at 22:11
  • Portrait is the default supported orientation for an unextended UIViewController, and presenting it will force a valid orientation. – Peter DeWeese Jul 06 '13 at 17:37