Carmichael Carmichael - 1 month ago 10
iOS Question

iPhone - Removing a presented view controller

On a view controller I have a button that will present another view controller. From the second view controller, I can go to other view controllers, but not necessarily back to the one that got me here. If this is the case, how can I remove the original view controller?

Answer

Your description is a bit unclear here. There could be 3 different cases here:

  1. Moving through navigation controller hierarchy
  2. Breaking out of navigation controller hierarchy to another view controller
  3. Just adding another view controller to current in navigation controller stack

In first case you can use methods of UINavigationController:

- (UIViewController *)popViewControllerAnimated:(BOOL)animated
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated

and use viewControllers property to navigate through the stack.

Ina second one, if you want to break out the hierarchy to one completely another view controller, then simply do it by:

[[[UIApplication sharedApplication] keyWindow].rootViewController dismissViewControllerAnimated:YES completion:nil];
[[UIApplication sharedApplication] keyWindow].rootViewController = newController;

or even better: add second line in completion block of first line.

Or in third case, if you want only to make one exception, but otherwise stay in navigation controller stack, then use methods:

- (void)addChildViewController:(UIViewController *)childController
- (void)removeFromParentViewController
Comments