TheJeff TheJeff - 1 year ago 187
iOS Question

Show Navigation Controller With Back Button

I am trying to programmatically show a view that I already have coded up, and give it a back button so that the user can easily pop back to my current view. Here is the only code I can get working, but it does not show a back button!

UIStoryboard *storyboard = self.storyboard;
UIViewController *root = [[[UIApplication sharedApplication] keyWindow] rootViewController];

UIViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@"Privacy"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];

navigationController.modalPresentationStyle = UIModalPresentationCurrentContext;

[root presentViewController:navigationController animated:YES completion:nil];

I've tried initializing the navigationController with the "root" viewController in the code above, then pushing the "controller" view controller via pushViewController. This crashes when I try to init with the "root" with a redacted stack trace.

How can I programmatically open a view with a back button to the current view?

I've looked everywhere on stackoverflow and this nuanced scenario is not addressed. Please help!

Answer Source

By far the easiest thing to do here is to embed the view I am using into a navigation controller. In the Interface builder, click on the view, then go to Editor -> Embed -> Navigation Controller.

From here, it is easy to hide the navigation bar itself in -(void)viewWillAppear:animated:

- (void)viewWillAppear:(BOOL)animated {
    //Hide the nav bar for the onboarding screens.
    [[self navigationController] setNavigationBarHidden:YES animated:YES];

Then here is the code to segue to another page with an automatically populated back button:

UIStoryboard *storyboard = self.storyboard;
UIViewController *controller = [storyboard instantiateViewControllerWithIdentifier:identifier];
[[self navigationController] pushViewController:controller animated:YES];
[[self navigationController] setNavigationBarHidden:NO animated:YES];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download