Mark Struzinski
Mark Struzinski

Reputation: 33471

How to set iPhone tab bar icon in code?

I am using the same ViewController for several different views.

When instantiating the ViewController for a specific view, is there an easy way to specify the tab bar icon via code?

Upvotes: 15

Views: 17787

Answers (4)

jnix
jnix

Reputation: 480

Correct way is : Add this below line in viewDidLoad

    [self.tabBarItem setImage:[UIImage imageNamed:@"<Image Name>"]];

to viewcontrollers which are set inside UITabBarController

Upvotes: 0

bendigi
bendigi

Reputation: 600

You can also do this in the AppDelegate, by declaring a UITabBarController iVar and pointing it to the applications tabBarController. You can access the individual titles using the items array. and the setTitle.

@synthesize tabBarController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.tabBarController = (UITabBarController*)self.window.rootViewController;
    NSArray* items = [self.tabBarController.tabBar items];
    [[items objectAtIndex:0] setTitle:@"Home"];
    [[items objectAtIndex:1] setTitle:@"Cool"];
    [[items objectAtIndex:2] setTitle:@"Stuff"];
    [[items objectAtIndex:3] setTitle:@"Settings"];
    return YES;
}

Upvotes: 1

Ty.
Ty.

Reputation: 3948

yourViewController.tabBarItem = [[UITabBarItem alloc]
initWithTitle:NSLocalizedString(@"Name", @"Name")
image:[UIImage imageNamed:@"tab_ yourViewController.png"]
tag:3];

The viewControllers are added to the tab bar, so the image and names should be set before the tab bar becomes visible (appDelegate if they are there on app start for instance). After that, you could use the above code to change the icon and text from the loadView or viewDidAppear within that viewController.

Upvotes: 25

newacct
newacct

Reputation: 122439

Yes. Your UITabBar has a property called items, which is an array of UITabBarItems for each tab bar item. You can create a UITabBarItem using the –initWithTitle:image:tag: constructor to use your own image, or the –initWithTabBarSystemItem:tag: constructor to use a system image.

Upvotes: 1

Related Questions