avatarbobo
avatarbobo

Reputation: 269

Adding TabBar item icons by code, not interface builder?

I'm making an app with the Dapp app, but I can't manage to add the tab bar icons correctly. So, is there a way to add the icons to the tab bar coding it? Like something on the AppDelegate, without using Interface Builder. Thanks!

Upvotes: 6

Views: 10301

Answers (2)

Mark Adams
Mark Adams

Reputation: 30846

UITabBarController derives all of the information necessary to create a tab bar item for each view controller by inspecting the view controller itself.

All you need to do is assign an array of view controllers using -setViewControllers:animated:.

Once a view controller is added to a tab bar controller, the tab bar controller will inspect the view controller's tabBarItem property. This tab bar item will be inserted into the tab bar controller's tab bar automatically. You can initialize a tab bar in each view controller programmatically. It looks something like this...

UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Title" image:[UIImage imageNamed:@"someImage"] tag:1];

or if you want to use one of the system items...

UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithSystemItem:UITabBarSystemItemFeatured tag:1];

I suggest you take a look at the UITabBarController, UITabBarItem and UIViewController class references and read up on the relevant properties. The docs are filled with indispensable information.

Upvotes: 6

user1078170
user1078170

Reputation:

Yeah, so if you have your 30x30 .png files in your resources, this should just be a matter of adding code like what follows. You would put this in your init method of the view controller associated with the tab bar index.

//get the tab bar item
            UITabBarItem *tbi = [self tabBarItem];

            //Give it a label
            [tbi setTitle:@"Item One"];

            //create a UIImage from a file
            UIImage *i = [UIImage imageNamed:@"MyItem.png"];

            //put that image on the tab bar item
            [tbi setImage:i];

Upvotes: 2

Related Questions