Search code examples
objective-cios5uiviewcontrolleruinavigationcontrolleruitableview

How to push a view to the navigation stack and remove the current one?


I would like to push a view into the navigation controller stack but remove the current one so when the users press back on the next view it does't take them to the previous view.

The flow in one direction could be one of these:

View X -> View 1 -> View 2 -> View 3    
View X -> View 1      ->      View 3

But the flow in the oposite direction is always like this:

View X <- View 1      <-      View 3

The problem is that I want to handle it on the View 2 Controller, doing it on the View 3 is easy overriding the back button action. The View 3 can be a lot of different views and I don't want to override the back button for all of them and check if the previous controller of the stack is the View 2 Controller. They all have the same parent class, so I can't override the back button for just the 'View 3 class' controllers.

I've tried this so the controller of the View 2 is not added into the navigation stack:

//Pop controller from stack before pushing
[self.navigationController popViewControllerAnimated:YES];
[self.navigationController pushViewController:controller animated:YES];

But once you pop it removes the view and doesn't push to the next controller

Other option with the same result

NSMutableArray *viewControllers = [NSMutableArray arrayWithArray: self.navigationController.viewControllers];
[viewControllers removeObjectIdenticalTo:self];
self.navigationController.viewControllers = viewControllers;
[self.navigationController pushViewController:controller animated:YES];

Solution

  • In regards to your last example that isn't pushing, does this work?

    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray: self.navigationController.viewControllers];
    [viewControllers removeObjectIdenticalTo:self];
    [viewControllers addObject:controller];
    [self.navigationController setViewControllers: viewControllers animated: YES];
    

    Since you set the controllers to an array of controllers without yourself, you might be setting your navigationController property to nil, making you unable to push the new one immediately after. It doesn't hurt to try, anyways.