简体   繁体   中英

Can't set tab bar icon iOS

I have a UITabBarController with a tab bar (of course), and I'm trying to set custom images to the tabs on my tab bar with the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];


    UITabBar *menuTab = self.tabBarController.tabBar;

    UIImage *friendImage = [UIImage imageNamed:@"friends_tab@2x.png"];
    UIImage *friendImageSelected = [UIImage imageNamed:@"friends_tab_selected@2x.png"];

    UITabBarItem *friendItem = [menuTab.items objectAtIndex:1];
    [friendItem initWithTitle:@"Friends" image:friendImage selectedImage:friendImageSelected];

}

on the [friendItem initWithTitle:@"Friends" image:friendImage selectedImage:friendImageSelected]; code line, i'm getting a warning "Expression Result unused" and the tab item neither get the image I set nor the text.

What am I doing wrong?

You can't access the items in a UITabBar that way. Basically, once a UITabBarItem is created, it's read-only. (The only exceptions to this are badgeValue , selectedImage , and title positioning.)

Also, you're getting the warning you are because init... methods returns a value, which you're not using. Calling init... methods on an existing object is just wrong.

Instead, what you need to do it something like this:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIViewController *vc            = self.viewControllers[1];
    UIImage *friendImage            = [UIImage imageNamed:@"friends_tab"];
    UIImage *friendImageSelected    = [UIImage imageNamed:@"friends_tab_selected"];
    UITabBarItem *friendItem        = [[UITabBarItem alloc] initWithTitle:@"Friends" image:friendImage selectedImage:friendImageSelected];
    vc.tabBarItem                   = friendItem;
}

Notice that I create a completely new UITabBarItem . When you have a UITabBarController , you are unable to have access to its UITabBar in the same way as one you create and manage yourself. Therefore, you need to access the tabBarItem property of the UIViewController you wish to modify.

You have already initialized your friend item--it was already made and you are retrieving it. You need to remove your initWithImage line andchange the title and image like properties, for example:

[friendItem setImage:@"myImage"];

and you can do the same for the title and the selected image. Does this work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM