ios 如何更改标签栏上的非活动图标/文本颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22767098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:52:13  来源:igfitidea点击:

How to change inactive icon/text color on tab bar?

iosobjective-cuitabbarcontrolleruitabbaruitabbaritem

提问by Pablo

How can I change inactive icon/text color on iOS 7 tab bar? The one in gray color.

如何更改 iOS 7 标签栏上的非活动图标/文本颜色?一种是灰色的。

enter image description here

在此处输入图片说明

回答by anka

You can also set the property Render Asof your tab bar images within your asset catalog directly. There you have the option to set the property to Default, Original Imageand Template Image.

您还可以Render As直接在资产目录中设置标签栏图像的属性。您可以选择将属性设置为Default,Original ImageTemplate Image

Set render option of image

设置图像的渲染选项

回答by Gabriel.Massana

In every first ViewController for each TabBar:

在每个 TabBar 的每个第一个 ViewController 中:

- (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];
}

The clue of this code is 'UIImageRenderingModeAlwaysOriginal':

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

Rendering Modes by Apple Documentation:

Apple 文档的渲染模式:

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

To change text color:

要更改文本颜色:

In AppDelegate:

在 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;
}

回答by Vaibhav Gaikwad

for changing color of unselect icons of tabbar

用于更改标签栏取消选择图标的颜色

For below iOS 10:

对于 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];
}

Above iOS 10:

iOS 10 以上:

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

回答by Steve Stomp

Instead adding it to every UIViewController, you can create an extension and alter the appearance of an UITabBarController

您可以创建一个扩展并更改 UITabBarController 的外观,而不是将其添加到每个 UIViewController

Change unselected icon color

更改未选中的图标颜色

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

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

Change selected icon color

更改选定的图标颜色

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

Change (un)selected title color

更改(取消)选定的标题颜色

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 扩展

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
    }
}

回答by Ahmed Lotfy

To change tab selection color instead blue color:

要更改选项卡选择颜色而不是蓝色:

  1. Select the tabItem.
  2. From "Show the Identity inspector" in the right side menu.
  3. Set "tintColor" attribute with your prefer color.
  1. 选择tabItem。
  2. 从右侧菜单中的“显示身份检查器”。
  3. 使用您喜欢的颜色设置“tintColor”属性。

enter image description here

在此处输入图片说明

回答by Umit Kaya

There is a better way without using each ViewController by only using appdelegate.m

只使用 appdelegate.m 不使用每个 ViewController 有更好的方法

In your AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptionsfunction, try this.

在你的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];

回答by Anchor

The new answer to do this programmatically as of iOS 10+ with Swift 3 is to use the unselectedItemTintColorAPI. For example, if you have initialized your tab bar controller inside your AppDelegate, it would looks like the following:

从带有 Swift 3 的 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

        // set the text color

        ...
    }

And for setting the selected and unselected text colors:

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

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

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

回答by kbokdia

In Swift 3.0 you can write it as follows

在 Swift 3.0 中你可以这样写

For unselected tab bar image

对于未选中的标签栏图像

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

For selected tab bar image

对于选定的标签栏图像

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

回答by Preeti Rani

Instead of adding rendering image code in each viewController for tabBarItem, use extension

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

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)
            }
        }
    }
}

Then call this in your UITabBarController class like

然后在您的 UITabBarController 类中调用它,例如

class CustomTabBarViewController: UITabBarController {

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

You will get output like : enter image description hereNOTE: Don't forget to assign CustomTabBarViewController class to your TabBarController in storyboard.

您将获得如下输出: 在此处输入图片说明注意:不要忘记将 CustomTabBarViewController 类分配给故事板中的 TabBarController。

回答by superarts.org

I think @anka's answer is quite good, and I also added the following code to enable tint color for highlighted items:

我认为@anka 的回答非常好,我还添加了以下代码来为突出显示的项目启用色调颜色:

    let image = UIImage(named:"tab-account")!.imageWithRenderingMode(.AlwaysTemplate)
    let item = tabBar.items![IC.const.tab_account] as! UITabBarItem
    item.selectedImage = image

Or in one line:

或者在一行中:

    (tabBar.items![IC.const.tab_account] as! UITabBarItem).selectedImage = UIImage(named:"tab-account")!.imageWithRenderingMode(.AlwaysTemplate)

So it looks like:

所以它看起来像:

tabbar

标签栏