Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change title of navbar based on which tab is selected?

I have an iOS app where there is a navigation controller as the root controller but at one part there is a tab bar to select between views in one of the nav bars. It looks similar to the iTunes app (navigation bar on top, tab bar on the bottom). I want the title of my navigation bar to change based on which tab is selected. I have two separate controller files for each tab. Here is what I have tried to use in each so far to fix this to no avail:

self.navigationItem.title = @"Title";
self.navigationController.navigationItem.title = @"title";
[self.navigationController setTitle:@"Live"];    
[self setTitle:@"Top Title"];

How do I change the NavBar title based on which tab is pressed?

like image 488
DCIndieDev Avatar asked May 16 '13 15:05

DCIndieDev


3 Answers

You change the title of the bar in the view controller that is currently being displayed.

So for example, in view controller A that you're showing in the tab controller, you might add:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self setTitle:@"A"];
    self.tabBarController.navigationItem.title = @"A";
}

Same goes for B, C, etc.

like image 65
The Kraken Avatar answered Oct 23 '22 06:10

The Kraken


In your ViewControllers that are in the tabs:

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.title = self.title;
}
like image 3
Mike Pollard Avatar answered Oct 23 '22 06:10

Mike Pollard


If the individual view controllers presented by the tab bar controller have their own navigation bars, then

[self setTitle:@"Foo"];

will set both the tab bar label, as well as the navigation bar title.

If the navigation controller is at the top level (i.e. the tab bar is inside the navigation controller), then you might have to set the navigation bar title's manually (and you'll want to do this in viewDidAppear rather than viewDidLoad, because these child controllers are not reloaded every time you switch), e.g.:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self.navigationController.navigationBar.topItem setTitle:@"Foo"];
}

Alternatively, you could do this navigation bar title adjustment in your UITabBarControllerDelegate method didSelectViewController.

If this doesn't do it, you might have to clarify your question, describing the hierarchy of controllers (e.g. is the tab bar controller inside navigation bar, or vice versa).

like image 2
Rob Avatar answered Oct 23 '22 04:10

Rob