Reputation: 1579
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.
Upvotes: 14
Views: 48140
Reputation: 1
[aController presentViewController:bController animated:NO completion:nil];
[bController presentViewController:cController animated:NO completion:nil];
when you want dismiss cController, you can do like this
[aController dismissViewControllerAnimated:NO completion:nil];
this is the flow chart.
aController → bController → cController
↑___________________________↓
Upvotes: 0
Reputation: 4791
Several things to consider.
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...
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.
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
Upvotes: 40
Reputation: 107
You should use UINavigationController to switch view controllers.
You are on View1 and add the following code on button click method.
View2 *View2Controller = [[View2 alloc] initWithNibName:@"View2" bundle:nil];
[self.navigationController pushViewController:view2Controller animated:YES];
Upvotes: -1
Reputation: 655
Use presentModalViewController
as follows
[self presentModalViewController:vc2 animated:YES completion:^(void){}];
and in the viewController1
use
[self dismissModalViewControllerAnimated:YES completion:^(void){}];
where ever you want to go back to previous controller.
Upvotes: 2
Reputation: 814
You should consider using UINavigationController
to switch view controllers. If your building target is iOS 5.0+, you can also use the new controller container concept: [mainViewController addChildViewController:childViewController]
.
Upvotes: 4