In this recipe we will learn how to detect the current orientation of the iOS device.
To begin, follow these simple steps as outlined:
ViewController.m
implementation file from the Project Navigator.viewDidLoad
method as shown in the following code snippet:- (void)viewDidLoad{ [super viewDidLoad]; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hasOrientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil]; }
hasOrientationChanged
method as shown in the following code snippet:-(void)hasOrientationChanged:(NSNotification *)notification { UIDeviceOrientationcurrentOrientation; currentOrientation = [[UIDevice currentDevice] orientation]; switch (currentOrientation) { case UIDeviceOrientationFaceUp: self.view.backgroundColor = [UIColor brownColor]; break; case UIDeviceOrientationFaceDown: self.view.backgroundColor = [UIColor magentaColor]; break; case UIDeviceOrientationPortrait: self.view.backgroundColor = [UIColor blueColor]; break; case UIDeviceOrientationPortraitUpsideDown: self.view.backgroundColor = [UIColor blueColor]; break; case UIDeviceOrientationLandscapeLeft: self.view.backgroundColor = [UIColor greenColor]; break; case UIDeviceOrientationLandscapeRight: self.view.backgroundColor = [UIColor redColor]; break; default: self.view.backgroundColor = [UIColor blackColor]; break; } }
Try changing the different views of orientation by pressing the Command + ;left arrow and Command + right arrow if you are running this within the iOS Simulator as shown in the screenshot:
What we covered in this recipe were the steps to create our example application. We began by telling our iOS device to start generating the notifications for each of the changes in the orientation that the device will take. We then set up an observer to the UIDeviceOrientationDidChangeNotification
class that gets fired each time the device changes its orientation. Next, we determined the current orientation that our iOS device is in by deriving this from the UIDeviceOrientation
class. Finally, we proceeded and determined what the current orientation is by using the switch…case
statements and then changed the background color of our view.
If you want to determine which way the iOS device is facing, you can get this information by using the UIDevice
class and then using its orientation property. When registering the UIDeviceOrientationDidChangeNotificaiton
notification method of the UIDevice
class, you are not
only told when the iOS device has been rotated between portrait and landscape views but also if the iOS device is facing up or down.
If you would like to find out more information on the UIDevice
class, you can refer to the Apple Developer documentation located on the link http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html.