Michael Mangold
Michael Mangold

Reputation: 1801

Present a Different View Controller After Dismissing a Modal View Controller

I present a modal view controller for various UI settings in an iOS app. One of those settings allows the user to select a different main view. When they hit "Done" I want to dismiss the modal view and have the newly-selected view controller appear, without a momentary delay where the old view controller segues to the new view controller. How could this be implemented?

Update:

Here is a method I successfully implemented using Eugene's technique, but without the app delegate. Instead, this implementation is specific to my scenario where a view controller in a navigation stack presents the modal view controller in a Utility app.

- (void)swapFrontSideViewController;
{
    UINavigationController *navigationVC = (UINavigationController *)[self presentingViewController];
    NSMutableArray *viewControllers      = [NSMutableArray arrayWithArray:navigationVC.viewControllers];
    UIViewControllerSubclass *selectedViewController = nil;
    if ([self.selectedFrontSide isEqualToString:FRONT_SIDE_NAME1]) {
        selectedViewController = [self.storyboard instantiateViewControllerWithIdentifier:FRONT_SIDE_NAME1];
    } else if ([self.selectedFrontSide isEqualToString:FRONT_SIDE_NAME2]) {
        selectedViewController = [self.storyboard instantiateViewControllerWithIdentifier:FRONT_SIDE_NAME2];
    }
    if (selectedViewController) {
        [viewControllers replaceObjectAtIndex:viewControllers.count -1 withObject:selectedViewController];
        [navigationVC setViewControllers:viewControllers];
        self.delegate = selectedViewController;
    } else {
        NSLog(@"Error: Undefined Front Side Selected.");
    }
}

Upvotes: 2

Views: 4225

Answers (1)

Eugene
Eugene

Reputation: 10045

- (IBAction)doDismiss:(id)sender {
  AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; // Get the app delegate
  NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:appDelegate.navigationController.viewControllers]; // fetch its navigationController viewControllers stack
  UIViewController *replacementController; //initialize replacement controller
  [viewControllers replaceObjectAtIndex:viewControllers.count -1 withObject:replacementController]; // replace the top view controller in stack with the replacement one
  [appDelegate.navigationController setViewControllers:viewControllers]; //change the stack
  [self dismissModalViewControllerAnimated:YES];
}

Upvotes: 3

Related Questions