如何在选项卡栏上更改未激活图标/文字的颜色?

61

我如何更改iOS 7标签栏上不活动图标/文本的颜色?即灰色的那一个。

输入图片描述


可能是在故事板中更改选定的选项卡栏项目颜色的重复问题。 - Marcelo Gracietti
1
@Marcelo Gracietti。请先检查日期。这不是重复的,你提到的那个才是。 - Pablo
20个回答

117

您还可以直接在资源目录中设置选项卡栏图像的呈现方式(Render As)属性。您可以选择将属性设置为默认(Default)原始图像(Original Image)模板图像(Template Image)

设置图像的呈现选项


我喜欢这个解决方案,但在iOS 8中似乎有一个bug:我使用原始图像作为正常状态的图片,使用模板图像作为选中状态的图片。正常状态的图片可以显示,但选中状态的图片却无法显示。还有其他人遇到过这个问题吗? - Hans One
@HansOne 可能您没有在选项卡栏项目中选择“Selected Image”属性,只选择了“Image”属性。 - Thomás Pereira
图像下方的文本仍然是灰色。 - user3722523

92

对于每个选项卡的第一个视图控制器:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // changing the unselected image color, you should change the selected image 
    // color if you want them to be different
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"yourImage_selectedImage"]
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    self.tabBarItem.image = [[UIImage imageNamed:@"yourImage_image"] 
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

这段代码的线索是“UIImageRenderingModeAlwaysOriginal”:

按照苹果文档的说明,有以下渲染模式:

UIImageRenderingModeAutomatic,          // Use the default rendering mode for the context where the image is used    
UIImageRenderingModeAlwaysOriginal,     // Always draw the original image, without treating it as a template
UIImageRenderingModeAlwaysTemplate,     // Always draw the image as a template image, ignoring its color information

更改文本颜色:

在AppDelegate中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Add this if you only want to change Selected Image color 
    // and/or selected image text
    [[UITabBar appearance] setTintColor:[UIColor redColor]];

    // Add this code to change StateNormal text Color,
    [UITabBarItem.appearance setTitleTextAttributes:
    @{NSForegroundColorAttributeName : [UIColor greenColor]} 
    forState:UIControlStateNormal];

    // then if StateSelected should be different, you should add this code
    [UITabBarItem.appearance setTitleTextAttributes:
    @{NSForegroundColorAttributeName : [UIColor purpleColor]} 
    forState:UIControlStateSelected];

    return YES;
}

5
在每个视图控制器中设置tabBarItem是不好的想法,因为它们不一定会立即实例化。但即使如此,在iOS 7上,现有的图像也会简单地消失。调试器显示图像已正确加载。它们具有透明度。 - Pablo
2
我的意思是,在每个选项卡的每个第一个 ViewController 中。 - Gabriel.Massana
图片消失了,就像我说的一样。 - Pablo
你的应用中收藏夹、最近使用和书籍等层次结构嵌入了导航控制器吗?如果是,我的模拟器测试没有问题。如果不是,则整个标签栏会消失。 - Gabriel.Massana
不,我根本没有导航控制器。 - Pablo
显示剩余8条评论

16

用于更改标签栏未选中图标的颜色。

iOS 10及以下版本:

// this code need to be placed on home page of tabbar    
for(UITabBarItem *item in self.tabBarController.tabBar.items) {
    item.image = [item.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

iOS 10及以上版本:

// this need to be in appdelegate didFinishLaunchingWithOptions
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor blackColor]];

1
如果您不必支持 iOS 10 及以下版本,则这是最好的答案。 - CBanga
同意CBanga的观点。这是最好的答案 - 一个函数覆盖所有的tabbar视图控制器。它还解决了等待每个tabbar视图控制器中的viewDidLoad方法运行的问题。不错。 - Peza
这行代码:[[UITabBar appearance] setUnselectedItemTintColor:[UIColor blackColor]]在iOS 13中无法正常工作! - Arash HF
感谢您在2021年学习OC。现在,OC的资料已经过时且很难找到。可以使用系统颜色来适应深色模式 [[UITabBar appearance] setUnselectedItemTintColor:UIColor.labelColor]; - Zhou Haibo
@ArashHF,你把它放在appdelegate didFinishLaunchingWithOptions里了吗?在我的端上它是可以工作的。 - Zhou Haibo
我无法在 IOS 15 Beta 8 中使用 setUnselectedItemTintColor - Hendrix

10

你可以创建一个扩展(extension),并改变UITabBarController的外观,而不是将其添加到每个UIViewController中。

更改未选中图标颜色

extension UITabBarController {
    override public func viewDidLoad() {
        super.viewDidLoad()

        tabBar.items?.forEach({ (item) -> () in
           item.image = item.selectedImage?.imageWithColor(UIColor.redColor()).imageWithRenderingMode(.AlwaysOriginal)
        })
    }
}

更改所选图标颜色

let tabBarAppearance = UITabBar.appearance()
tabBarAppearance.tintColor = UIColor.blackColor()

更改(未)选中标题颜色

let tabBarItemApperance = UITabBarItem.appearance()
tabBarItemApperance.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Edmondsans-Bold", size: 10)!, NSForegroundColorAttributeName:UIColor.redColor()], forState: UIControlState.Normal)
tabBarItemApperance.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Edmondsans-Bold", size: 10)!, NSForegroundColorAttributeName:UIColor.blackColor()], forState: UIControlState.Selected)

UIImage扩展

extension UIImage {
    func imageWithColor(color1: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        color1.setFill()

        let context = UIGraphicsGetCurrentContext()
        CGContextTranslateCTM(context!, 0, self.size.height)
        CGContextScaleCTM(context!, 1.0, -1.0);
        CGContextSetBlendMode(context!, .Normal)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
        CGContextClipToMask(context!, rect, self.CGImage!)
        CGContextFillRect(context!, rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }
}

方法 imageWithColor 是从哪里来的? - Aaron
@Aaron 抱歉,我漏掉了。这是 UIImage 的一个扩展。我已经更新了我的答案。 - srstomp
@Aaron,我现在不再使用这个扩展程序了。现在我只需要在Xcode中更改图像的渲染模式为“模板图像”,然后更改tintColor。 - srstomp
当您在标签栏控制器之后引用视图控制器时,这种方法无法正常工作。 - azizj

7

有一个更好的方法,只使用appdelegate.m文件而不是每个视图控制器。

在您的AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函数中,尝试以下内容。

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UITabBar *tabBar = tabBarController.tabBar;

// repeat for every tab, but increment the index each time
UITabBarItem *firstTab = [tabBar.items objectAtIndex:0];

// also repeat for every tab
firstTab.image = [[UIImage imageNamed:@"someImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
firstTab.selectedImage = [[UIImage imageNamed:@"someImageSelected.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

7

将选项卡的选择颜色改为非蓝色:

  1. 选择tabItem。
  2. 从右侧菜单中选择“显示标识检查器”。
  3. 将“tintColor”属性设置为您喜欢的颜色。

enter image description here


5

不要在每个tabBarItem的viewController中添加渲染图像代码,而是使用扩展(extension)

extension UITabBar{
     func inActiveTintColor() {
        if let items = items{
            for item in items{
                item.image =  item.image?.withRenderingMode(.alwaysOriginal)
                item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.green], for: .normal)
                item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.white], for: .selected)
            }
        }
    }
}

然后在您的UITabBarController类中调用此函数,例如:
class CustomTabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.inActiveTintColor()
    }
}

您将获得以下输出: 在此输入图片描述 注意:不要忘记在Storyboard中将CustomTabBarViewController类分配给您的TabBarController。

4

在iOS 10+和Swift 3中,以编程方式实现此操作的新答案是使用unselectedItemTintColor API。例如,如果您已经在AppDelegate中初始化了标签栏控制器,则应该如下所示:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        ...

        let firstViewController = VC1()
        let secondViewController = VC2()
        let thirdViewController = VC3()


        let tabBarCtrl = UITabBarController()
        tabBarCtrl.viewControllers = [firstViewController, secondViewController, thirdViewController]

        // set the color of the active tab
        tabBarCtrl.tabBar.tintColor = UIColor.white

        // set the color of the inactive tabs
        tabBarCtrl.tabBar.unselectedItemTintColor = UIColor.gray

        // set the text color

        ...
    }

设置选中和未选中的文本颜色:

let unselectedItem = [NSForegroundColorAttributeName: UIColor.green]
let selectedItem = [NSForegroundColorAttributeName: UIColor.red]

self.tabBarItem.setTitleTextAttributes(unselectedItem, for: .normal)
self.tabBarItem.setTitleTextAttributes(selectedItem, for: .selected)

你节省了我的时间。非常感谢。 - Shawn Baek

4

我认为是时候使用

UITabBar未选中项的颜色设置

/// Unselected items in this tab bar will be tinted with this color. Setting this value to nil indicates that UITabBar should use its default value instead.
    @available(iOS 10.0, *)
    @NSCopying open var unselectedItemTintColor: UIColor?

只需将此行添加到应用程序完成启动中即可。

UITabBar.appearance().unselectedItemTintColor = {your color}
// Example
UITabBar.appearance().unselectedItemTintColor = .black

Tab Bar unselectedItemTintColor appearance


3
在Swift 3.0中,你可以这样写:
对于未选择的标签栏图像。
viewController.tabBarItem.image = UIImage(named: "image")?.withRenderingMode(.alwaysOriginal)

对于选定的选项卡栏图像

viewController.tabBarItem.selectedImage = UIImage(named: "image")?.withRenderingMode(.alwaysOriginal)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接