Search code examples
iosuiviewcontrolleruinavigationcontroller

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

Solution

  • 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)