简体   繁体   中英

Make new UINavigationController then empty stack of old navigation controller programatically

Without using storyboards, I want to:

  1. Create a UINavigationController (let's call it NC_A) in the app delegate, then push a bunch of UIViewControllers onto it. (This doesn't need to be explained. It's just step one.)

  2. Then, from the last UIViewController on the stack, I want to jump off to a new UINavigationController (NC_B).

  3. After the new NC_B's root view is shown, behind the scenes on NC_A pop back to NC_A's root view so that when I return to it, the root view is shown.

Here is objective-c solution: you can put both NC_A and NC_B navigation controllers in master navigation controller and let that handle the switching.

1. Setup:

UIViewController * rootVC_A = [[UIViewController alloc]init];
UINavigationController * NC_A = [[UINavigationController alloc]initWithRootViewController: rootVC_A];

UIViewController * rootVC_B = [[UIViewController alloc]init];
UINavigationController * NC_B = [[UINavigationController alloc]initWithRootViewController: rootVC_B];

UINavigationController * RootNavigationController = [[UINavigationController alloc]initWithRootViewController: NC_A];

2.Pushing to NC_A

for(int i = 0; i < 5; i ++)
{
    UIViewController * randomVC = [[UIViewController alloc]init];
    [NC_A pushViewController:randomVC animated: true];
}

3. Jump to NC_B

[RootNavigationController pushViewController: NC_B animated: YES];

4. Pop Back NC_A

[NC_A popToRootViewController];

First, prepare NC_A :

let rootA = UIViewController(...)
let navA = UINavigationController(rootViewController: rootA)

navA should be your window's root view controller or presented some other way. Push a bunch of view controllers on navA .

Now prepare NC_B . We will present it modally on top of your NC_A stack. We can use the completion handler on presentViewControllerAnimated to pop NC_A back to its root view controller.

let rootB = UIViewController(...)

let navB = UINavigationController(rootViewController: rootB)

navA.presentViewController(navB, animated: true) { () -> Void in
    navA.popToRootViewControllerAnimated(true)
}

Now, when you call dismissViewControllerAnimated on NC_B , NC_A will be popped to its root view controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM