UINavigationController popToRootViewController, an

2020-02-02 10:04发布

I have a tabBarController with two tabs, first of which contains an instance of NavigatorController. The navigatorController is initiated with a custom viewController "peersViewController" that list all the network peers on a tableView. Upon selecting a peer, an instance of "FilesListViewController" (which list files in the c:\ directory) is pushed into the navigationController stack.

In this filesListViewController I have a button to let it navigate to say documents directory. To do this I'd wired the interface to call a gotoDirectory:(NSString*)path method in the rootViewController:

- (void)gotoDirectory:(NSString*)path {
     [[self navigationController] popToRootViewControllerAnimated:YES];
     NSArray *files = [self getFilesFromPeerAtPath:path];
     FilesListViewController *filesVC = [[FilesListViewController alloc] initWithFiles:files];
     [[self navigationController] pushViewController:filesVC animated:YES];
     [filesVC release];
}

However, when I press that button, the navigationController did pop my view to the root view controller, but then the FilesListViewController that I instantiated did not appear. From the log, I know that the custom initWithFiles method was indeed called and network stuffs did happen to get the file names.

Something else is screwy about this. I tried clicking on the second tab and then click back to the first tab, and huala! the file names I needed are there. It looks like the data and the filesListViewController was indeed pushed into the navigatorController stack, but the display was not refreshed but stuck at the screen of rootViewController (peersViewController).

Am I doing anything wrong?

--Ben.

-- Edited like 15 minutes after posting the question. I'd found a workaround, but it bothers me that pop and then push doesn't work.

- (void)gotoDirectory:(NSString*)path {
     PeersListViewController *rootViewController = (PeersListViewController*)[[[self navigationController] viewControllers] objectAtIndex:0];
     [[self navigationController] setViewControllers:[NSArray arrayWithObject:rootViewController]];
     FilesListViewController *filesVC = [[FilesListViewController alloc] initWithFiles:files];
     [[self navigationController] pushViewController:filesVC animated:YES];
     [filesVC release];
}

It doesn't seem like the navigationController should be circumvented this way, and I'd probably have to release all the viewControllers that were in the original stack. This does however work on the iphone 3.0 simulator.

If I'm using this code though, how should the memory release be handled? should I get the original NSArray of viewcontrollers and release everything?

6条回答
Deceive 欺骗
2楼-- · 2020-02-02 10:16

The problem and solution to this issue is actually extremely simple.

Calling [self.navigationController popToRootViewControllerAnimated:YES] sets self.navigationController to nil. When you subsequently call [self.navigationController pushViewController:someOtherViewController] you are effectively sending a message to nil, which does nothing.

To workaround, simply set up a local reference to the navigationController and use that instead:

UINavigationController * navigationController = self.navigationController;
[navigationController popToRootViewControllerAnimated:NO];
[navigationController pushViewController:someOtherViewController animated:YES];

As stated by Jason, the popToRootViewController must be performed without animation for this to work correctly.

Thanks go to jpimbert on the Apple forums for pointing this out.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-02 10:16

I got a very similar problem (but without using tab).

I got three viewController : main(root), form and result. when the UINavigationController stack is

"main -> result"

on a btnClick I do a popToRootViewControllerAnimated then a push of the formViewCtrl. in order to have

"main -> form"

the navbar title and back button label are correct and the formViewCtrl's event are called. BUT, I still see the main view.

Here is my "solution"

After doing some test, I found out that without the animation to go to the rootViwCtrl this work fine. So I only use the animation to push viewCtrl.

iPhone 3.0, problem found on device & simulator.

If i got something new, i will update/comment my post.

查看更多
走好不送
4楼-- · 2020-02-02 10:29

You can actually keep the "Go back" animation, followed by the "Go forward" animation by basically delaying the push animation till after the pop animation is complete. Here is an example:

(Note: I have an NSString variable called "transitionTo" in my appDelegate that's initially set to @"")...First, set that variable to an NSString you can detect for later. Then, pop the controller to give you a nice screen transition back to the root:

appDelegate.transitionTo = @"Another";
[detailNavigationController popToRootViewControllerAnimated:YES];

Then inside the rootviewcontroller's class, use the viewDidAppear method:

-(void)viewDidAppear:(BOOL)animated
{
    AppDelegate *appDelegate =(AppDelegate*) [UIApplication sharedApplication].delegate;
    if([appDelegate.transitionTo isEqualToString:@"Another"])
    {
        [self transitionToAnotherView];
        appDelegate.transitionTo = @"";
    }
}

-(void)transitionToAnotherView
{
    // Create and push new view controller here
    AnotherViewController *controller = [[AnotherViewController alloc] init];

    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:backButton];

    [[self navigationController] pushViewController:controller animated:YES];
}

So basically, pop to the root...when the transition finishes at "viewDidAppear"...then push the next view. I happened to keep a variable to tell you which view you wish to transition to (with @"" meaning not to do a transition in the case that I want to stay on this screen).

查看更多
时光不老,我们不散
5楼-- · 2020-02-02 10:32

Nick Street's answer works great if you want to popToRootViewController and subsequently push another VC.

VC1 -> VC2 -> VC3: hit the back button from VC3 => VC2, then VC1, here OK

However, when VC1 pushes VC2, which in turn pushes VC3, then going back to VC1 directly from VC3 does not work as wished:

I've implemented in VC3's -(void)viewWillDisappear:(BOOL)animated:

-(void)viewWillDisappear:(BOOL)animated{

    ...
    [self.navigationController popToRootViewControllerAnimated:YES];
}

I also tried to implement it in the "back button", same result: upon hitting the back button from VC3 to go back to VC1: it breaks. The actual VC is VC1, but the navigation bar is still VC2. Playing with other combinations, I get VC1's navBar on VC2. Total mess.

Loda mentioned something about timing. I think that's the main issue here. I've tried a few things, so maybe I'm missing out something here, but this is what worked for me, at last:

In VC3:

-(void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    // notify VC2
    [[NSNotificationCenter defaultCenter] postNotificationName:backFromV3 object:self];
}

In VC2:

-(void)viewDidLoad {

    ...

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backFromV3)
                                                 name:@"BackFromV3"
                                               object:nil];
}

-(void)backFromV3{
    [NSTimer scheduledTimerWithTimeInterval:0.5 
                                 target:self
                               selector:@selector(backToRootViewController)
                               userInfo:nil
                                repeats:NO];
}

-(void)backToVC1 {
    self.navigationItem.rightBarButtonItem = nil;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

Of course, do the necessary cleaning.

The timer is critical here. If 0, it breaks. 0.5 seems to be alright.

That works perfectly for me. A little heavy, but I have not been able to find anything that does the trick.

查看更多
beautiful°
6楼-- · 2020-02-02 10:33

I found a workaround but I cannot explain why it is working: 1. First push the needed controller. 2. Then pop to the one you want to.

This is totally illogical, but it works for my case. Just to make things clear, I'm using it in the following scenario: First Screen -> Goes to Loading Screen -> Second Screen When I'm on the Second Screen, I don't want to have the Loading Screen in the stack and when click back I should go to the First Screen.

Regards, Vesko Kolev

查看更多
唯我独甜
7楼-- · 2020-02-02 10:35

I see that this question about popping to the root and then pushing a new ViewController is pretty prevalent, and this post is viewed a lot, so I wanted to add my bit to help other new guys out, especially those using Xcode 4 and a storyboard.

In Xcode 4, you have a storyboard. Let's say you have these view controllers: HomeViewController, FirstPageViewController, SecondPageViewController. Make sure to click each of them and name their identifiers by going to the Utilities pane->Attributes Inspector. We'll say they're named Home, First, and Second.

You are Home, then you go to First, then you want to be able to go to Second and be able to press the back button to go back to Home. To do this, you want to change your code in FirstPageViewController.

To expand on the example, make a button in FirstPageViewController in the storyboard. Ctrl-drag that button into FirstPageViewController.m. In there, the following code will achieve the desired outcome:

    // Remember to add #import "SecondPageViewController.h" at the top
    SecondPageViewController *secondView = [self.storyboard instantiateViewContorllerWithIdentifier:@"Second"];
    UINavigationController *navigationController = self.navigationController;
    NSArray *array = [navigationController viewControllers];
    // [array objectAtIndex:0] is the root view controller
    NSArray *viewControllersStack = [NSArray arrayWithObjects:[array objectAtIndex:0], secondView, nil];
    [navigationController setViewControllers:viewControllersStack animated:YES];

Basically, you're grabbing the view controllers, arranging them in a stack in the order you want, and then having the navigation controller use that stack for navigation. It's an alternative to pushing and popping.

查看更多
登录 后发表回答