Jul 28

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.

  1. The Device generates these notifications on request. So, the first thing we need to do is tell it to start generating them.
  2. The Controller has to register to listen for these events.
  3. 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");
    }
}
Tagged with:
preload preload preload