Search code examples
iphoneobjective-ciosipad

Best way to switch View Controller in iOS


I have 2 view controllers in my project. Inside View Controller1 I want to switch to View Controller 2 by press of a button. Currently I do this

- (IBAction)startController2:(id)sender {

viewController1 vc2 = [[viewController2 alloc] init];
self.view = vc2.view;
}

This seems to work fine, but there is a big delay (4 secs) between the button press and second view controller appears. If I call the viewController2 directly from the AppDelegate things load faster. What am I doing wrong here. Any help is greatly appreciated.


Solution

  • Several things to consider.

    Part 1: "What am I doing wrong here"?

    1. You definitely didn't mean to do self.view = vc2.view. You just put one view controller in charge of another view controller's view. What you probably mean to say was [self.view addSubview:vc2.view]. This alone might fix your problem, BUT...

    2. Don't actually use that solution. Even though it's almost directly from the samples in some popular iPhone programming books, it's a bad idea. Read "Abusing UIViewControllers" to understand why.

    Part 2: What you should be doing

    It's all in the chapter "Presenting View Controllers from Other View Controllers".

    It'll come down to either:

    • a UINavigationController, (see the excellent Apple guide to them here) and then you simply [navigationController pushViewController:vc2]

    • a "manually managed" stack of modal view controllers, as andoabhay suggests

    • explicitly adding a VC as child of another, as jason suggests