Sunday, 21 August 2011

Better way to handle switching between multiple view controllers?

Was looking at this sample code from Apple called "AlternateViews" which demonstrates the switching between 2 View Controllers when the device orientation changes.

I found a few interesting things about the code:

1. The "PortraitViewController" is loaded first, it then loads the "LandscapeViewController" in the viewDidLoad() of "PortraitViewController".

2. There's this new piece of code which I never seen before (as below) using NSNotificationCenter, which sets to call "orientationChanged" method when the orientation changed.


[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:)  name:UIDeviceOrientationDidChangeNotification object:nil];


3. When the orientation changed to Landscape, it calls the following "presentModalViewController" code to switch to the "LandscapeViewController"


[self presentModalViewController:self.landscapeViewController animated:YES];


4. When the orientation changed back to Portrait, it calls the following code to switch back.


[self dismissModalViewControllerAnimated:YES];


This way of switching between multiple view controllers is new to me, plus the way the change of orientation been handled is quite interesting too. Will certainly give it a try on some of my projects.

No comments:

Post a Comment