1

A user arrives at this viewController from the previous one through a push segue, so I want there to be a back button in the UINavigationBar to allow them to return.

Normally this back button would appear by default if I right clicked on the viewController in storyboard and selected Embed in > Navigation Controller, but doing this is causing crashes, and I prefer doing things programmatically, so I decided to do it in viewDidLoad like so:

    // Nav bar
    UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];

    // Back Button
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:self action:@selector(Back)];
    self.navigationItem.leftBarButtonItem = backButton;

    [self.view addSubview:navbar];

This successfuly adds a navigation bar up top, but it doesn't add the back button as expected. I've tried the solutions given here, here, and here, but none have solved the problem.

Community
  • 1
  • 1
Andrew
  • 3,839
  • 10
  • 29
  • 42
  • This is exactly why you shouldn't do it in code, it pollutes your controllers with view creation and just opens the door to a clunky UI with weird behaviour. Use storyboards for as much UI stuff as possible, thats what they are made for, keep the programmatic UI stuff as limited as possible. – trapper Jan 20 '16 at 07:24

1 Answers1

0

You have constructed a UINavigationBar and a UIBarButtonItem but never connected the two.

UINavigationController manages a UINavigationBar for you and sets it's topItem to be the navigationItem of the topmost view controller in the navigation stack. If you need to build your own navigation bar then you need to manage it's item stack yourself. Take a look at UINavigationBar's - pushNavigationItem:animated: method.

However given that you seem to want the look and functionality of a UINavigationController it is unclear to me why you are adding a UINavigationBar view yourself instead of using that container view controller.

Jonah
  • 17,918
  • 1
  • 43
  • 70
  • That's a great point. How would I then display the container? It isn't appearing as it is now unless I embed it in a navigation controller, and that's causing crashes. – Andrew Jan 20 '16 at 03:18