66

我有一个包含 5 个项目的 UITabBar。我想更改所有项目的未选择颜色。这些项目未在 UIViewController 类中声明(我构建了它们并链接了 Storyboard 中的视图)。

有没有这样的代码:[[UITabBar appearance] set***UN***SelectedImageTintColor:[UIColor whiteColor]];

4

14 回答 14

100

iOS 10 及更高版本中,有 3 种可能的简单解决方案:

A. 来自代码的实例(Swift):

self.tabBar.unselectedItemTintColor = unselectedcolor

B. 来自 IB 的实例:

添加一个关键路径:unselectedItemTintColor类型:Color

C. 全局外观(Swift):

UITabBar.appearance().unselectedItemTintColor = unselectedcolor

于 2016-10-15T20:08:57.417 回答
96

据我所知,这在 iOS 7 下不起作用。特别是,选项卡栏的tintColor将定义选定选项卡的颜色,而不是未选定选项卡的颜色。如果您想更改 iOS 7 中的默认设置,似乎您必须实际使用不同的图标(使用您喜欢的未选中选项卡的颜色)并设置文本的颜色。

此示例应将选定的选项卡着色为红色,并将其他选项卡渲染为绿色。在 TabBarController 中运行此代码:

// set color of selected icons and text to red
self.tabBar.tintColor = [UIColor redColor];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor redColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];


// set color of unselected text to green
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor greenColor], NSForegroundColorAttributeName, nil]
                                         forState:UIControlStateNormal];

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

// this way, the icon gets rendered as it is (thus, it needs to be green in this example)
item0.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
item0.selectedImage = [UIImage imageNamed:@"selected-icon.png"];

如果仅在故事板中设置图标,则只能控制所选选项卡的颜色(tintColor)。所有其他图标和相应的文本将以灰色绘制。

也许有人知道在 iOS 7 下采用颜色的更简单方法?

于 2013-08-25T21:38:04.727 回答
71

扩展@Sven Tiffe 对 iOS 7 的回答,您可以让您的代码自动为故事板中添加的未选择的 UITabBar 图像着色。以下方法将使您不必创建两组图标图像(即选中与未选中)并且必须以编程方式加载它们。添加类别方法 imageWithColor:(请参阅 -我如何在 iOS 和 WatchKit 中更改图像 tintColor)到您的项目然后将以下内容放入您的自定义 UITabBarController viewDidLoad 方法中:

// set the selected colors
[self.tabBar setTintColor:[UIColor whiteColor]];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];


UIColor * unselectedColor = [UIColor colorWithRed:184/255.0f green:224/255.0f blue:242/255.0f alpha:1.0f];

// set color of unselected text
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:unselectedColor, NSForegroundColorAttributeName, nil]
                                         forState:UIControlStateNormal];

// generate a tinted unselected image based on image passed via the storyboard
for(UITabBarItem *item in self.tabBar.items) {
    // use the UIImage category code for the imageWithColor: method
    item.image = [[item.selectedImage imageWithColor:unselectedColor] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

在 UIImage+Overlay.m 上创建一个名为 UIImage+Overlay 的类别(摘自此答案 ):

@implementation UIImage(Overlay)

- (UIImage *)imageWithColor:(UIColor *)color1
{
        UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0, self.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetBlendMode(context, kCGBlendModeNormal);
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        CGContextClipToMask(context, rect, self.CGImage);
        [color1 setFill];
        CGContextFillRect(context, rect);
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
}
@end
于 2014-06-08T13:29:43.910 回答
26

SO说我不能删除接受的答案(我试过),但显然,有很多评论认为这不适用于iOS 7。

请参阅下面的其他答案以及更多赞成票,或@Liam 对此答案的评论中的链接。


仅适用于 iOS 6

它应该像这样简单:

[[UITabBar appearance] setTintColor:[UIColor grayColor]]; // for unselected items that are gray
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]]; // for selected items that are green
于 2012-07-16T21:32:07.090 回答
22

iOS 10 及更高版本中的 Swift 版本 -

UITabBar.appearance().tintColor = UIColor.gray
UITabBar.appearance().unselectedItemTintColor = UIColor.gray
于 2017-08-01T13:23:16.447 回答
18

翻译 user3719695 对 Swift 的回答,现在使用扩展:

UIImage+Overlay.swift

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, CGBlendMode.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
  }
}

customTabBar.swift

override func viewDidLoad() {
  super.viewDidLoad()
  for item in self.tabBar.items! {
    item.image = item.selectedImage?.imageWithColor(unselectedColor).imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    //In case you wish to change the font color as well
    let attributes = [NSForegroundColorAttributeName: unselectedColor]
    item.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
  }
}
于 2015-10-17T00:29:18.717 回答
7

我不得不将代码移入viewWillAppear,因为viewDidLoad尚未设置图像。

斯威夫特 4 翻译

import Foundation
import UIKit

extension UIImage {
    func with(color: UIColor) -> UIImage {
        guard let cgImage = self.cgImage else {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(.normal)
        let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        context.clip(to: imageRect, mask: cgImage)
        color.setFill()
        context.fill(imageRect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        return newImage
    }
}

class MYTabBarController: UITabBarController {

    let unselectedColor = UIColor(red: 108/255.0, green: 110/255.0, blue: 114/255.0, alpha: 1.0)
    let selectedColor = UIColor.blue()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Unselected state colors
        for item in self.tabBar.items! {
            item.image = item.selectedImage!.with(color: unselectedColor).withRenderingMode(.alwaysOriginal)
        }
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor : unselectedColor], for: .normal)

        // Selected state colors
        tabBar.tintColor = selectedColor
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor : selectedColor], for: .selected)
    }
}
于 2016-08-06T03:41:23.473 回答
7

iOS 13 中有一个新的外观 API。要正确使用 Xcode 11.0 为标签栏项目的图标和文本着色,您可以像这样使用它:

  if #available(iOS 13.0, *)
     {
        let appearance = tabBar.standardAppearance
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
        appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.blue]
        appearance.stackedLayoutAppearance.normal.iconColor = UIColor.black
        appearance.stackedLayoutAppearance.selected.iconColor = UIColor.blue
        tabBar.standardAppearance = appearance
    } 
    else 
    {
        tabBar.unselectedItemTintColor = UIColor.black
        tabBar.tintColor = UIColor.blue
    }
于 2020-06-17T09:39:29.453 回答
2

从 iOS 10+ 开始,以编程方式执行此操作的新方法是使用unselectedItemTintColorAPI。例如,如果您在 中初始化了标签栏控制器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

        ...
    }
于 2016-10-29T05:11:27.953 回答
2

或者只是不编码斯威夫特 4Xcode 10.1

  1. 使用Interface Builder添加UITabBar您的视图控制器。
  2. 在左侧面板中选择添加的视图。
  3. 键入cmd + alt + 3或单击Show the Identity Inspector右侧面板。
  4. 在部分User Defined Runtime Attributes中单击加号按钮以添加新属性并将其称为unselectedItemTintColor(参见此处)。
  5. 不离开上一步中的部分(参见第 4 步),在Type选择Color类型列下。
  6. 最后,在部分下设置必要的颜色Value
  7. 编译你的项目
  8. 超过。恭喜。

在此处输入图像描述

于 2018-12-26T10:52:50.537 回答
1

参考这里的答案:iOS 7中的UITabBar tint

您可以为选定和未选定的标签栏按钮设置色调颜色,如下所示:

[[UIView appearanceWhenContainedIn:[UITabBar class], nil] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];

第一行通过设置 UIView 包含在选项卡栏中时的 tintColor 来设置未选择的颜色(在此示例中为红色)。请注意,这仅设置未选择图像的色调颜色 - 它不会更改其下方文本的颜色。

第二行将选项卡栏的选定图像色调设置为绿色。

于 2014-04-10T07:52:14.790 回答
1

Swift 4 版本(没有隐式展开 Optionals):

UIImage+Overlay.swift

import UIKit

extension UIImage {
    func with(color: UIColor) -> UIImage? {
        guard let cgImage = self.cgImage else {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        if let context = UIGraphicsGetCurrentContext() {
            context.translateBy(x: 0, y: size.height)
            context.scaleBy(x: 1.0, y: -1.0)
            context.setBlendMode(.normal)
            let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            context.clip(to: imageRect, mask: cgImage)
            color.setFill()
            context.fill(imageRect)
            if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
                UIGraphicsEndImageContext();
                return newImage
            }
        }
        return nil;
    }
}


CustomTabBarController.swift

class CustomTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.0, *) {
            self.tabBar.unselectedItemTintColor = UIColor.init(white: 1, alpha: 0.5)
        } else {
            // Fallback on earlier versions
            if let items = self.tabBar.items {
                let unselectedColor = UIColor.init(white: 1, alpha: 0.5)
                let selectedColor = UIColor.white
                // Unselected state colors
                for item in items {
                    if let selectedImage = item.selectedImage?.with(color: unselectedColor)?.withRenderingMode(.alwaysOriginal) {
                        item.image = selectedImage
                    }
                }
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : unselectedColor], for: .normal)

                // Selected state colors
                tabBar.tintColor = selectedColor
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : selectedColor], for: .selected)
            }
        }

        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "overpass-light", size: 12)!, NSAttributedStringKey.foregroundColor: UIColor.white], for: UIControlState.normal)
    }
}
于 2017-11-15T14:26:40.937 回答
0

@JoeGalid 的imageWithColor:Xamarin 解决方案:

using CoreGraphics;
using UIKit;

namespace Example
{
    public static class UIImageExtensions
    {
        public static UIImage ImageWithColor(this UIImage image, UIColor color)
        {
            UIGraphics.BeginImageContextWithOptions(image.Size, false, image.CurrentScale);

            color.SetFill();

            var context = UIGraphics.GetCurrentContext();

            context.TranslateCTM(0, image.Size.Height);
            context.ScaleCTM(1.0f, -1.0f);
            context.SetBlendMode(CoreGraphics.CGBlendMode.Normal);

            var rect = new CGRect(0, 0, image.Size.Width, image.Size.Height);
            context.ClipToMask(rect, image.CGImage);
            context.FillRect(rect);

            var newImage = UIGraphics.GetImageFromCurrentImageContext() as UIImage;
            UIGraphics.EndImageContext();

            return newImage;
        }
    }
}

然后在设置标签栏项目时使用它:

var image = UIImage.FromBundle("name");
barItem.Image = image.ImageWithColor(UIColor.Gray).ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
barItem.SelectedImage = image.ImageWithColor(UIColor.Red).ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
于 2016-09-06T12:18:08.463 回答
0

使用swift未选择标签栏的颜色

  1. 获取 TabBarViewController 的参考
  2. 使用以下代码。

       [You tabbar controller name]?.tabBar.unselectedItemTintColor = [color name here]
    

希望它会有所帮助。

于 2020-02-20T19:22:02.697 回答