如何更改iOS7中未选择的tabbaritem颜色?

时间:2013-10-29 15:09:25

标签: ios objective-c ios7 uitabbar

在iOS 7之前我使用了

[[UITabBar appearance] setTintColor:[UIColor redColor]];

但现在它只绘制了所选项目,我已经阅读了一些建议,但我无法完成如何操作,我也使用了它:

[self.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"openbookwp4.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"openbookwp4.png"]];

这把我想要的图标放在我想要的颜色上,但是只有在我选择该标签后,例如,当我打开应用程序时,标签看起来正常,但是在我按下第二个标签并返回到第一个标签后,第二个标签现在有我想要的颜色。没有图像很难解释,但我无法发布图像......

3 个答案:

答案 0 :(得分:20)

此代码适用于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];

根据需要设置前景色。

还要影响未选择的标签栏图标:

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

如果它不起作用,唯一的方法是选择和未选择状态的图像:

// 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"];

答案 1 :(得分:0)

在我的情况下,问题是我只在viewDidLoad中定义了标签栏项。如果这样做,很明显只有在加载相应选项卡的视图后才会设置图像,但最初不会设置(仅当选择了第一个选项卡时)。

我的解决方案是在视图控制器的init方法中定义自定义选项卡项,然后即使尚未加载控制器视图,也可以看到未选择的图像。

答案 2 :(得分:0)

来自Nikos的回答

对于swift 2. *它看起来像这样

 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)