How to change the unselected tabbaritem color in iOS7?

喜你入骨 提交于 2019-11-30 10:26:21

This code works on iOS 7.

[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:10.0f],
                                                    NSForegroundColorAttributeName : [UIColor colorWithRed:.5 green:.5 blue:.5 alpha:1]
                                                    } forState:UIControlStateNormal];

Set foreground color as you like.

To affect also the non selected tabbar icons:

[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor greenColor], UITextAttributeTextColor, nil]
                                         forState:UIControlStateNormal];

If it does not work the only way is with images for selected and unselected states:

// set selected and unselected icons
UITabBarItem *item = [self.tabBar.items objectAtIndex:0];

// this way, the icon gets rendered as it is (thus, it needs to be green in this example)
item.image = [[UIImage imageNamed:@"unselected-icon.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

// this icon is used for selected tab and it will get tinted as defined in self.tabBar.tintColor
item.selectedImage = [UIImage imageNamed:@"selected-icon.png"];

In my case the problem was that I defined the tab bar items in viewDidLoad only. If you do this, it is clear that the images are only set once the view of the corresponding tab has been loaded, but not at first (when only the first tab is selected).

My solution was to define the custom tab items in the view controller's init method, then the unselected images are visible even when the controller's view has not been loaded yet.

Following on from Nikos Answer

For swift 2.* it would look like this

 UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:.Normal)

    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:.Selected)

    let Item1 = self.items![0]
    Item.image = UIImage(named: "Icon1")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

    let Item2 = self.items![1]
    Item2.image = UIImage(named: "Icon2")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

    let Item3 = self.items![2]
    Item3.image = UIImage(named: "Icon3")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!