Yahoo
Yahoo

Reputation: 4187

Moving View Controller to the top of navigation stack iOS

How do I move a VC pushed into navigation stack to be on top?

Suppose I pushed it in this order

Push VC1 
Push VC 2
Push VC 3

So now currently I have VC3 on top. How do I programmatically bring VC2 to front? So that the stack becomes

VC1,VC3,VC2

Upvotes: 2

Views: 2649

Answers (3)

Duncan C
Duncan C

Reputation: 131418

To the best of my knowledge, you don't.

You would need to use popToViewController:animated: to pop to VC1. Then your view controller stack would be

  VC1
  root view controller

(You said you pushed VC1. A navigation controller has a root view controller which is always at the bottom of the stack.)

Edit:

As @AlexKosyakov pointed out, it is possible to edit a navigation controller's navigation stack by manipulating the array. (Cudos and an up vote to him for pointing that out.)

However, I would say that you should NOT do that. A navigation stack is an Apple-provided user interface model that provides a consistent user experience, and creates an expectation on the part of the user. If I see the visual cues of a navigation stack (push animation, back buttons, etc) then I have the expectation, conscious or unconscious, that pressing the back button will take me back to the previous screen, and that the order of screens in the stack will not change out from under me.

Upvotes: 1

Alex Kosyakov
Alex Kosyakov

Reputation: 2176

As a developer, you have an access to navigation controller stack by manage its viewControllers array:

NSArray *currentStack = self.navigationController.viewControllers

enter image description here

Discussion The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array.

Assigning a new array of view controllers to this property is equivalent to calling the setViewControllers:animated: method with the animated parameter set to false.

It is simple an array, that holds the vcs that are currently in nav's stack and you can manage this array like the others:

NSMutableArray *tempArray = [NSMutableArray arrayWithArray: currentStack];

[tempArray removeObjectAtIndex:1];
[tempArray addObject:secondVC];

self.navigationController.viewControllers = tempArray;

There are a set of available methods that you can play with:

enter image description here

Hope it helps)

Upvotes: 4

picciano
picciano

Reputation: 22701

First, let me state that that is a very unusual thing to need to do. Normally, you would just pop VC 3 off the stack to go back.

That said, you can get the array of view controllers from vc3.navigationController.viewControllers, rearrange the items in the array and set the viewControllers property back on the navigation controller.

Upvotes: 1

Related Questions