Isuru
Isuru

Reputation: 31283

Navigation Controller from a View Controller

I'm using .xib files in an app. And I want to have two view controllers normal way and from the third view controller, embed it in a navigation view controller. Here's an illustration of how I want it.

enter image description here

I know I can embed a navigation controller in a modally presented view controller like this.

let firstVC = FirstViewController(nibName: firstViewController, bundle: nil)
let navController = UINavigationController(rootViewController: firstVC)
presentViewController(navController, animated: true, completion: nil)

But if I embed it in a navigation controller and push it, the app crashes with the error Pushing the same view controller instance more than once is not supported.

let firstVC = FirstViewController(nibName: firstViewController, bundle: nil)
let navController = UINavigationController(rootViewController: firstVC)
navController.pushViewController(firstVC, animated: true)

Is it possible to do this at all? If so, can someone please explain how?

Thank you.

NOTE: Don't confuse the code snippets with the diagram above. The firstViewController in the code is not the first view controller in the diagram.

Upvotes: 4

Views: 1554

Answers (2)

meim
meim

Reputation: 740

  1. use the first view controller as the root view controller of the UINavigationController
  2. use the following method to present your next view controller

[self.navigationController pushViewController:vc animated: YES];

  1. in the viewWillAppear method, if you wanna hide the navigation bar, use

[self.navigationController setNavigationBarHidden:YES animated:animated];

If you wanna show the navigation bar, use

[self.navigationController setNavigationBarHidden:NO animated:animated];

Upvotes: 1

Ardra Thambi
Ardra Thambi

Reputation: 137

Suppose that FirstViewcontroller,Secondviewcontroller,Thirdviewcontroller are the three view controllers. then the transition from second to third view controller use the code given below.

Secondviewcontroller *second=[[Secondviewcontroller alloc]init];
UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController: second];
[self presentViewController:nav animated:NO completion:nil];

Upvotes: 1

Related Questions