Suchi
Suchi

Reputation: 10039

Calling pushViewController after a presentViewController does not work

I am presenting my view controller like this -

[self.navigationController presentViewController:self.thingContainerViewController animated:YES completion:nil]; //self.navigationController not nil here

This shows a UITableView. I want to push a VC on the navigation stack from here. But the self.navigationController is nil at this point. Any idea how to make this work?

[self.navigationController pushViewController:otherContainer animated:YES]; //self.navigationController is nil at this point

Upvotes: 4

Views: 5845

Answers (3)

vincent
vincent

Reputation: 73

UIViewController.navigationController means:

The nearest ancestor in the view controller hierarchy that is a navigation controller.

on the other hand, presentViewController makes new view controller out of hierarchy, the new view controller has no navigation controller ancestor unless you assign one to it by [[UINavigationController alloc] initWithRootViewController:self.thingContainerViewController] as @Dima mensioned.

so, the solution is

UINavigationController *targetVCWithNavigationControllerAncestor = [[UINavigationController alloc] initWithRootViewController:self.thingContainerViewController];
[self.navigationController presentViewController:targetVCWithNavigationControllerAncestor animated:YES completion:nil];

then you can push new view controller from self.thingContainerViewController

Upvotes: 0

HardikDabhi
HardikDabhi

Reputation: 2952

Swift 3/Swift 4

first of all you need to set navigation controller on which you want to present.After that do navigation process on your second view controller.

  • Example like that

       let firstPresentVC = FirstVC(nibName:"FirstVC",bundle:nil)
       let navVC = UINavigationController(rootViewController:firstPresentVC)
       navVC.isNavigationBarHidden = true
       self.present(navVC, animated: true, completion:nil)
    

Now You are on Present Stack With Navigation

You can push after that

let secondPushVC = secondPushVC(nibName:"secondPushVC",bundle:nil)
self.navigationController?.pushViewController(secondPushVC, animated: true)

Upvotes: 3

Dima
Dima

Reputation: 23634

You need to wrap the view controller you are presenting in a navigation controller in order to be able to use the push and pop methods.

So for the first step:

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:self.thingContainerViewController];

Then:

[self.navigationController presentViewController:navigationController animated:YES completion:nil];

If you do that, your code will work.

Upvotes: 3

Related Questions