Initial Landscape orientation issue on iOS solved

I have searched for a solution how to implement a ViewController that supports only LandscaleLeft and LandscapeRight mode. Most solutions I found on stackoverflow and other forums using a setOrientationMode selector on the device object:

NSNumber *value = [NSNumber numberWithInt:
  UIInterfaceOrientationLandscapeLeft];

[[UIDevice currentDevice] setValue:value 
                            forKey:@"orientation"];

this could probably work for you, but it uses a non official selector. You may think of this: it is impossible for the program to actually physically turn around your device, but that is what your code would look like.

I finally ended up with a solution that does rotate the interface instead of the device. The following code is a working ViewController that does the trick by calling [UIViewController attemptRotationToDeviceOrientation].

/////////////////////////////////////
/// VIEW CONTROLLER CODE
@interface StartViewController : UIViewController
-(id) initWithWindow:(UIWindow *)window;
@property (nonatomic, retain) UIWindow * window_;
@end // @interface StartViewController

@implementation StartViewController

-(void)dealloc
{
     //cleanup code
     self.window_ = nil;
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
  (UIInterfaceOrientation) interfaceOrientation
{
    return YES;
}

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

-(void)viewWillAppear:(BOOL)animated
{
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeLeft | 
           UIInterfaceOrientationMaskLandscapeRight;
}

-(id) initWithWindow:(UIWindow *) window
{
    [super init];
    self.window_ = window;
    return self;
}
@end // implementation StartViewController
/////////////////////////////////////

/////////////////////////////////////
/// APPLICATION CODE:
- (void)applicationDidFinishLaunching:(UIApplication*)application
{
    UIWindow * window = [[[UIWindow alloc] initWithFrame:
      [[UIScreen mainScreen] bounds]] autorelease]; 

    window.rootViewController = [[[StartViewController alloc] 
      initWithWindow:window] autorelease];

    [window makeKeyAndVisible];
    [[UIDevice currentDevice] 
      beginGeneratingDeviceOrientationNotifications];
}
/////////////////////////////////////

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.