Thursday 10 November 2011

Handle Orientation in iPhone/iPad


  
By default iOS5 and earlier supports only portrait mode orientation, if we want to enable all orientation we have to implement shouldAutorotateToInterfaceOrientation method in UIViewController.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES; //YES for supporting all orientation. NO- disable orientation
}

iOS have four orientations are 
   UIInterfaceOrientationPortrait
   UIInterfaceOrientationPortraitUpsideDown
   UIInterfaceOrientationLandscapeLeft    
   UIInterfaceOrientationLandscapeRight
if dont want any one orientation, then check the orientation and return NO

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if(UIInterfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    return NO; //disable UIInterfaceOrientationLandscapeLeft orientation
else
   return YES;
}

Find device orientation changes :-

//implement this method to find the device orientation changes - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { } If your application doesn't call didRotateFromInterfaceOrientation method then you have to add your controller as child view controller in then rootview controller. - (void)viewDidLoad { [super viewDidLoad]; [self addChildViewController:(UIViewController*) self.yourChildController]; }

Changing UIView when Orientation change :-

Here i created two UIView and assigned when orientation changed. I created two dashboard UIView for portrait and landscape , get the IBOutlet from XIB 
Views.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight ) { self.view = self.LandscapeView; } else { self.view = self.portraitView; } return YES; }
Download the source code for better understanding : https://github.com/karthikprabhuA/iPhoneOrientationHandling



No comments:

Post a Comment