In UINavigationController speak, we “push” new controllers onto the stack (go forward), and we “pop” them off the stack (go back). The navigation controller handles all this for us.
If you want to go back exactly one view controller, here’s how you can do it programmatically:
// pop back to previous controller NSArray *myControllers = self.navigationController.viewControllers; int previous = myControllers.count - 2; UIViewController *previousController = [myControllers objectAtIndex:previous]; [self.navigationController popToViewController:previousController animated:YES];
First we access the array of all view controllers and count it. We subtract one (because arrays are 0 based), and another one to go back in history – hence we go “minus 2”. Then we pop to view controller just behind the current one.
Test if the returned value is less than zero though…
If you want to go back all the way to the root view controller, there’s a method for that:
// pop back to root controller [self.navigationController popToRootViewControllerAnimated:YES];