You can override willMoveToParentViewController . This method is called before your view controller has been added or removed from the container view controller (for example, UINavigationController ). When it is added, the parent parameter contains the container view controller; when it is deleted, the parent parameter is zero.
At this point, you can remove (without animation) the second controller of the last view in the navigation stack as follows:
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 can also delete several or add new ones. Just make sure that when you are finished, your array contains at least 2 view controllers with the last invariable (the last one is deleted, and after this method is automatically called, it is automatically deleted from the array).
Also note that this method can be called more than once with the nil parameter. For example, if you try to display the view controller by dragging the edge, but interrupt it in the middle, the method will be called every time you try. Be sure to add additional checks to make sure that you do not remove more view controllers than you want.
source share