Balázs Vincze
Balázs Vincze

Reputation: 357

How to add another UIViewController to an existing UINavigationController

I have an app with two View Controllers. The first one is embedded in a Navigation Controller and has a navigation bar, I present the second View Controller programatically after a certain method has ended in the first View Controller. This works fine, but this way the second View Controller is not part of the Navigation Controller stack and does not really have any relationship with the first View Controller. Like this, I can't take advantage of the Navigation Controller. Any thoughts on how could I solve this?

I present the second view controller with this code after the user has picked an image from the photo library:

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
  pickedImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
  [self dismissViewControllerAnimated:YES completion:NULL];
  UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  ViewController *viewController = (ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"viewControllerID"];
  viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  [self presentViewController:viewController animated:YES completion:nil];
}

Upvotes: 2

Views: 2229

Answers (2)

aytunch
aytunch

Reputation: 1444

instead of the

[self presentViewController:viewController animated:YES completion:nil];

use

[self.navigationController pushViewController:viewController animated:YES];

So that the VC2 is also in the same Navigation stack

Your final code looks like this:

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; 
    ViewController *viewController = (ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"viewControllerID"];    
    viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self.navigationController pushViewController:viewController animated:YES];
}

Upvotes: 1

Michel Marqués
Michel Marqués

Reputation: 161

Try this:

YourController *controller = [[YourController alloc] init];

[self.navigationController pushViewController:controller animated:YES];

Upvotes: 0

Related Questions