Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 858
user1191140 Avatar asked Apr 22 '12 05:04

user1191140


People also ask

How do I move between view controllers?

Control-drag from the button in the first view controller into the second view controller. In the dialog that pops up, select show. A top bar should appear in the second view controller and there should be a connection between our first view controller to our second view controller.

How do I go back to the previous view controller in iOS 4?

Open your storyboard where your different viewController are located. Tap the viewController you would like your navigation controller to start from. On the top of Xcode, tap "Editor" -> Tap embed in.


1 Answers

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

like image 158
ckhan Avatar answered Sep 28 '22 13:09

ckhan