popping and pushing view controllers in same action
MapsViewController *aViewController = [[MapsViewController alloc] initWithNibName:@"MapsViewController" bundle:nil]; // locally store the navigation controller since // self.navigationController will be nil once we are popped UINavigationController *navController = self.navigationController; // retain ourselves so that the controller will still exist once it's popped off [[self retain] autorelease]; // Pop this controller and replace with another [navController popViewControllerAnimated:NO];//not to see pop [navController pushViewController:aViewController animated:YES];//to see push or u can change it to not to see.
Or
MapsViewController *aViewController = [[MapsViewController alloc] initWithNibName:@"MapsViewController" bundle:nil];UINavigationController *navController = self.navigationController;//Get all view controllers in navigation controller currentlyNSMutableArray *controllers=[[NSMutableArray alloc] initWithArray:navController.viewControllers] ;//Remove the last view controller[controllers removeLastObject];//set the new set of view controllers[navController setViewControllers:controllers];//Push a new view controller[navController pushViewController:aViewController animated:YES];
In Swift:
let newVc = UIViewController()var vcArray = self.navigationController?.viewControllersvcArray!.removeLast()vcArray!.append(newVc)self.navigationController?.setViewControllers(vcArray!, animated: false)
In case newVc exists in a Storyboard:
let storyboard = UIStoryboard(name: "Main", bundle: nil)let newVc = storyboard.instantiateViewControllerWithIdentifier("YourViewControllerIdentifier") as! UIViewControllervar vcArray = self.navigationController?.viewControllersvcArray!.removeLast()vcArray!.append(newVc)self.navigationController?.setViewControllers(vcArray!, animated: false)
Taken from https://stackoverflow.com/users/1619554/tomer-peled 's solution, so others can find it more easily.
This appears to be the best way to do it for iOS8:
UIViewController *newVC = [[UIViewController alloc] init]; // Replace the current view controller NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[[self navigationController] viewControllers]];[viewControllers removeLastObject]; [viewControllers addObject:newVC]; [[self navigationController] setViewControllers:viewControllers animated:YES];