How can I change the view controller the default navigation back button takes me to? The back button usually takes you back to the previous view controller. But what if I wa
You can override willMoveToParentViewController. This method is called before your view controller is added in or removed from a container view controller (like a UINavigationController). When it is being added, the parent parameter contains the container view controller, when it is being removed, the parent parameter is nil.
At this point you can remove (without animation) the second to last view controller in the navigation stack like so :
Objective-C
- (void)willMoveToParentViewController:(UIViewController *)parent
{
[super willMoveToParentViewController:parent];
if (parent == nil) {
NSArray *viewControllers = self.navigationController.viewControllers;
NSUInteger viewControllersCount = viewControllers.count;
if (viewControllersCount > 2) {
NSMutableArray *mutableViewControllers = [NSMutableArray arrayWithArray:viewControllers];
[mutableViewControllers removeObjectAtIndex:(viewControllersCount - 2)];
[self.navigationController setViewControllers:[NSArray arrayWithArray:mutableViewControllers] animated:NO];
}
}
}
Swift
override func willMoveToParentViewController(parent:UIViewController?)
{
super.willMoveToParentViewController(parent)
if (parent == nil) {
if let navigationController = self.navigationController {
var viewControllers = navigationController.viewControllers
var viewControllersCount = viewControllers.count
if (viewControllersCount > 2) {
viewControllers.removeAtIndex(viewControllersCount - 2)
navigationController.setViewControllers(viewControllers, animated:false)
}
}
}
}
You could also remove more than one or add new ones. Just make sure that when you are finished your array contains at least 2 view controllers with the last one unchanged (the last one is the one being removed and it will be removed from the array automatically after this method is called).
Also note than this method can be called more than once with a nil parameter. For example if you try to pop the view controller using the edge swipe but abort in the middle, the method will be called each time you try. Be sure to add additional checks to make sure that you don't remove more view controllers than you want.