Wednesday, 29 May 2013

TO check device orientation when rotating device and need to change in views

iOS Development

Add below lines of code in your viewDidLoad method and perform action as required

- (void)viewDidLoad

{

[super viewDidLoad];

 [self setOrientation];

}

-(void)setOrientation
{
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(deviceOrientationDidChangeNotification:)
     name:UIDeviceOrientationDidChangeNotification
     object:nil];
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
        // portrait
        [self portraitView];
    } else {
        // landscape
        [self landscapeView];
    }
    

}

- (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

    if(orientation == 1 || orientation == 2) // Landscape
    {
        [self portraitView];
    }
    else if(orientation == 3 || orientation == 4) // Portrait
    {
        [self landscapeView];
    }
}