iPhone Objective-C: programmatically change the title of a tab bar item in a 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 the tab is clicked. 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, which loads into another tab, but obviously something is wrong, since I get the left operand error.

How to achieve what I'm trying to do?

+7
objective-c iphone
source share
2 answers

Try setting the title to awakeFromNib instead of viewDidLoad. The view for the view controller does not actually load until you need the view, and the tab bar controller by default does not access the view controller view until you select it (which is why you saw the name change when you select the tab) .

Since nib creates the view controller to begin with (assuming you built your tab bar controller in IB), awakeFromNib will be called as soon as the view controller is created before the tab bar controller can ask what the title is.

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

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

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

However, this will not work since the title property does not exist. In fact, I see no way to change the header of the UITabBarItem after it is initialized. You will need to use the UITabBar setItems:animated: method to immediately set the entire group of elements. But it will not be fun.

I am sure this will be a violation of Apple HIG, so there is no easy way to do this using the current API. Review your design and ask yourself why you want to change the names of the tabs that will confuse your users.

+4
source share

All Articles