I’m working on an application that requires switching from a List View in portrait mode into a Cover Flow View when the device is rotated into landscape mode. This means, a Controller needs to know when a rotation has occurred and present the correct view. This was my first opportunity to play with Notifications.
- The Device generates these notifications on request. So, the first thing we need to do is tell it to start generating them.
- The Controller has to register to listen for these events.
- A Selector is provided as a callback when an event occurs.
Here is the code snippet that manages this:
- (void)viewDidLoad {
[super viewDidLoad];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceDidRotate:)
name:@"UIDeviceOrientationDidChangeNotification"
object:nil];
}
- (void)deviceDidRotate:(NSNotification *)notification {
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationLandscapeLeft ||
orientation == UIDeviceOrientationLandscapeRight)
{
NSLog(@"Sideways");
} else {
NSLog(@"Portrait");
}
}