【问题标题】:How to change inactive icon/text color on tab bar?如何更改标签栏上的非活动图标/文本颜色?
【发布时间】:2014-05-11 02:50:08
【问题描述】:

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

【问题讨论】:

标签: ios objective-c uitabbarcontroller uitabbar uitabbaritem


【解决方案1】:

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

【讨论】:

  • 我喜欢这个解决方案,但iOS 8 中似乎存在一个错误:我使用原始图像für 正常状态和模板图像用于选定状态。正常图像有效,但所选图像不出现。还有其他人经历过吗?
  • @HansOne 可能你没有在选项卡栏项中选择“选定图像”属性,只选择了“图像”属性。
  • 图片下面的文字还是灰色的
【解决方案2】:

在每个 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];
}

这段代码的线索是'UIImageRenderingModeAlwaysOriginal':

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

更改文字颜色:

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

【讨论】:

  • 在每个 viewController 中设置 tabBarItem 是个坏主意,因为它们不一定会立即实例化。但即使在那之后,在 iOS 7 上,现有图像也会消失。调试器显示图像已正确加载。它们具有 Alpha 透明度。
  • 我的意思是,在每个 TabBar 的每个第一个 ViewController 中。
  • 图片消失了,就像我说的那样。
  • 您的应用程序中的收藏夹、最近阅读、书籍的层次结构嵌入在导航控制器中?如果是,我的模拟器中的测试可以正常工作。如果不是,则整个 TabBar 会消失
  • 不,我根本没有导航控制器。
【解决方案3】:

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

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

【讨论】:

  • 如果你不需要支持iOS 10以下,这是最好的答案。
  • 同意CBanga。这是最好的答案 - 一个涵盖所有标签栏视图控制器的功能。它还消除了等待 viewDidLoad 方法在每个标签栏视图控制器中运行的问题。不错。
  • 这一行:[[UITabBar appearance] setUnselectedItemTintColor:[UIColor blackColor]] 在 iOS 13 中不起作用!
  • 谢谢,2021 年向 Swift 学习 OC。如今,OC材料确实已经过时且难得一见。可以使用系统颜色来采用暗模式 [[UITabBar appearance] setUnselectedItemTintColor:UIColor.labelColor];
  • @ArashHF,你把它放在appdelegate didFinishLaunchingWithOptions 里了吗,它对我有用吗?
【解决方案4】:

除了将它添加到每个 UIViewController 之外,您还可以创建一个扩展并更改 UITabBarController 的外观

更改未选中的图标颜色

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 对不起。错过了。它是 UIImage 的扩展。我更新了我的答案
  • @Aaron 我实际上不再使用这个扩展了。现在我只需将 Xcode 中图像的渲染模式更改为“模板图像”并更改 tintColor。
  • 当故事板在 tabbarcontroller 之后引用视图控制器时,这不起作用
【解决方案5】:

有一个更好的方法,不使用每个 ViewController,只使用 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];

【讨论】:

    【解决方案6】:

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

    1. 选择tabItem。
    2. 来自右侧菜单中的“显示身份检查器”。
    3. 用您喜欢的颜色设置“tintColor”属性。

    【讨论】:

      【解决方案7】:

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

      【讨论】:

      • 你节省了我的时间。非常感谢
      【解决方案8】:

      不要在每个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)
                  }
              }
          }
      }
      

      然后在你的 UITabBarController 类中调用它

      class CustomTabBarViewController: UITabBarController {
      
          override func viewDidLoad() {
              super.viewDidLoad()
              tabBar.inActiveTintColor()
          }
      }
      

      你会得到如下输出: 注意:不要忘记将 CustomTabBarViewController 类分配给故事板中的 TabBarController。

      【讨论】:

        【解决方案9】:

        我觉得是时候使用了

        UITabBar unselectedItemTintColor 外观

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

        【讨论】:

          【解决方案10】:

          在 Swift 3.0 中你可以这样写

          对于未选中的标签栏图片

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

          对于选中的标签栏图片

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

          【讨论】:

            【解决方案11】:

            我觉得@anka 的回答很好,我还添加了以下代码来为突出显示的项目启用 tint color:

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

            或者在一行中:

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

            所以它看起来像:

            【讨论】:

              【解决方案12】:

              您只需将此代码放在您的第一个 ViewController 中,为 TabBarViewController (ViewDidload) 调用:

              - (void)viewDidLoad {
                  [super viewDidLoad];
                  // Do any additional setup after loading the view.
                  [self loadIconsTabBar];
              }
              
              -(void) loadIconsTabBar{
                      UITabBar *tabBar = self.tabBarController.tabBar;
                      //
                      UITabBarItem *firstTab = [tabBar.items objectAtIndex:0];
                      UITabBarItem *secondTab = [tabBar.items objectAtIndex:1];
                      firstTab.image = [[UIImage imageNamed:@"icono1.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
                      firstTab.selectedImage = [[UIImage imageNamed:@"icono1.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
                      secondTab.image = [[UIImage imageNamed:@"icono2.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
                      secondTab.selectedImage = [[UIImage imageNamed:@"icono2.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
                  }
              

              【讨论】:

                【解决方案13】:

                您只需将此代码放在名为 (didFinishLaunchingWithOptions) 的 appDelegate.m 中:

                [UITabBarItem.appearance setTitleTextAttributes:
                @{NSForegroundColorAttributeName : [UIColor whiteColor]}
                                                       forState:UIControlStateNormal];
                
                
                [UITabBarItem.appearance setTitleTextAttributes:
                @{NSForegroundColorAttributeName : [UIColor orangeColor]}
                                                       forState:UIControlStateSelected];
                
                [[UITabBar appearance] setTintColor:[UIColor whiteColor]]; // for unselected items that are gray
                [[UITabBar appearance] setUnselectedItemTintColor:[UIColor whiteColor]]; 
                

                【讨论】:

                • setUnselectedItemTintColor 仅适用于 iOS 10
                【解决方案14】:

                如果您正在寻找 iOS 11 swift 4 解决方案,请在 appDelegate 中执行类似的操作。这会将所有未选中的变为黑色。

                func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
                    // Override point for customization after application launch.
                
                    UITabBar.appearance().unselectedItemTintColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 1)
                
                    return true
                }
                

                【讨论】:

                • 适用于 iOS 10
                【解决方案15】:

                更改已选标签栏项目颜色的最佳方法是在 appdelegate didFinishLaunchingWithOptions 方法上添加单个代码

                UITabBar.appearance().tintColor = UIColor(red: 242/255.0, green: 32/255.0, blue: 80/255.0, alpha: 1.0)
                

                会改变选中项的文字颜色

                【讨论】:

                  【解决方案16】:

                  您可以通过界面生成器完成所有操作,查看此答案,它显示了如何同时进行活动和非活动,"Change tab bar item selected color in a storyboard"

                  【讨论】:

                    【解决方案17】:

                    对于 Swift 3:

                        // both have to declare in view hierarchy method
                        //(i.e: viewdidload, viewwillappear) according to your need.
                    
                        //this one is, when tab bar is selected
                        self.tabBarItem.selectedImage = UIImage.init(named: "iOS")?.withRenderingMode(.alwaysOriginal)
                    
                        // this one is when tab bar is not selected
                        self.tabBarItem.image = UIImage.init(named: "otp")?.withRenderingMode(.alwaysOriginal)
                    

                    【讨论】:

                      【解决方案18】:

                      这对我有用 SWIFT 3

                      viewConroller.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "image")?.withRenderingMode(.alwaysOriginal),
                                                      selectedImage:  UIImage(named: "image"))
                      

                      【讨论】:

                        【解决方案19】:

                        Swift 解决方案: 对于未选择的项目: 在每个 ViewController -> ViewDidLoad()

                        self.tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "PHOTO_NAME")?.imageWithRenderingMode(.AlwaysOriginal), selectedImage: UIImage(named: "NAME"))
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 2018-03-09
                          • 2017-02-03
                          • 2013-06-11
                          • 1970-01-01
                          • 2013-09-12
                          • 1970-01-01
                          • 1970-01-01
                          相关资源
                          最近更新 更多