Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone Objective-C: Programmatically change title of tab bar item in tab bar created using IB?

Right now, I am setting the title in the viewDidLoad of the root view of the tab, which only changes when I click on the tab. I want this to be set before I select the tab. I tried something like:

[[self.parentViewController.tabBarController.tabBar.items objectAtIndex:2] title] = @"string";

in the first view that loads in another tab, but there is clearly something wrong since I get a left operand error.

What is the correct way to achieve what I am trying to do?

like image 670
Ayaka Nonaka Avatar asked Jul 29 '10 03:07

Ayaka Nonaka


2 Answers

[[self.parentViewController.tabBarController.tabBar.items objectAtIndex:2] title] = @"string";

The syntax is slightly off here. You probably wanted something like:

[[self.parentViewController.tabBarController.tabBar.items objectAtIndex:2].title = @"string";

However, that won't work, since there is no title property to set. In fact, there's no way I can see to change a UITabBarItem's title once it's been initialized. You'll have to use UITabBar's setItems:animated: method to set the entire group of items at once. But it won't be fun.

I bet this would be an Apple HIG violation, which is why there's no easy way to do it with the current API. Rethink your design and ask yourself why you want to change the names of the tabs, which will confuse your users.

like image 136
Shaggy Frog Avatar answered Sep 22 '22 02:09

Shaggy Frog


Try setting the title in awakeFromNib instead of viewDidLoad. The view for a view controller is not actually loaded until you need the view, and the tab bar controller by default doesn't access the view of a view controller until you actually select it (which is why you saw the title change when you selected the tab).

Since the nib is creating the view controller to start with (assuming you have built your tab bar controller in IB) awakeFromNib will be called as soon as the view controller has been built, before the tab bar controller can ask what the title is.

like image 32
Kendall Helmstetter Gelner Avatar answered Sep 21 '22 02:09

Kendall Helmstetter Gelner