Question

I have a UINavigationController (A) which has a few subviews which also are UIViewControllers (B and C). The main UINavigationController (A) rides inside of a UITabViewController (D).

I'm trying to push a view controller within B: [self.navigationController pushViewController... etc]

Now, the backBarButtonItem comes through with the wrong text. Instead of saying 'Back', it just says 'Item'. This is likely because one of the view controllers in my chain has its title set to 'Item' or maybe it is nil altogether.

My question is, where is the backBarButtonItem generated from?

I tried a few different things that didn't work. I tried each of these lines of code within B right before I pushed the view controller. None of them worked.

self.presentingViewController.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"... etc

self.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"... etc

self.navigationController.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"... etc

I'd like to learn the principle here so that I truly understand where this item is being populated from and what the right way to do it is.

Was it helpful?

Solution

Let's say your C controller is on top of the navigation controller's stack, and your B controller is under that. E.g.

navigationController.viewControllers = @[ bViewController, cViewController ];

So the navigation controller is displaying cViewController.view.

The navigation controller uses the second-to-top controller on its stack to configure the back button. In this case, it uses bViewController to configure the back button. This is its algorithm:

UINavigationItem *navigationItem = bViewController.navigationItem;
UIBarButtonItem *barItem = navigationItem.backBarButtonItem;

if (barItem.image != nil) {
    show a back button containing barItem.image;
}

else if (barItem.title != nil) {
    if (barItem.title.length > 0) {
        show a back button containing barItem.title;
    } else {
        don't show a back button;
    }
}

else if (navigationItem.title != nil) {
    if (navigationItem.title.length > 0) {
        show a back button containing navigationItem.title;
    } else {
        don't show a back button;
    }
}

else {
    show a back button containing @"Back";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top