【问题标题】:Unselected UITabBar color?未选择 UITabBar 颜色?
【发布时间】:2012-07-15 19:13:21
【问题描述】:

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

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

【问题讨论】:

标签: ios uitabbarcontroller uitabbar uitabbaritem


【解决方案1】:

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
    }

【讨论】:

    【解决方案2】:

    使用 swift 取消选择标签栏的颜色

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

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

    希望它会有所帮助。

    【讨论】:

      【解决方案3】:

      或者只是不编码Swift 4Xcode 10.1

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

      【讨论】:

        【解决方案4】:

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

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

        self.tabBar.unselectedItemTintColor = unselectedcolor
        

        B.来自 IB 的实例:

        添加密钥路径:unselectedItemTintColor 类型:Color

        C.全局外观(Swift):

        UITabBar.appearance().unselectedItemTintColor = unselectedcolor
        

        【讨论】:

        • 您的回答让我意识到,如果您使用情节提要,我们也可以通过在属性检查器中添加“unselectedItemTintColor”键路径来使用“用户定义的运行时属性”来做到这一点。谢谢!
        • 如果您还支持较低版本(
        【解决方案5】:

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

        UITabBar.appearance().tintColor = UIColor.gray
        UITabBar.appearance().unselectedItemTintColor = UIColor.gray
        

        【讨论】:

        • 你是 SVIM 的吗?
        • @DheerajD 不,我不是
        【解决方案6】:

        我不得不将代码移动到viewWillAppear,因为viewDidLoad 中的图像尚未设置。

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

        【讨论】:

          【解决方案7】:

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

          【讨论】:

            【解决方案8】:

            从 iOS 10+ 开始,以编程方式执行此操作的新方法是使用 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
            
                    ...
                }
            

            【讨论】:

              【解决方案9】:

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

              【讨论】:

                【解决方案10】:

                据我所知,这在 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 下采用颜色的更简单方法?

                【讨论】:

                • 注意 - 'UITextAttributeTextColor' 已弃用:首先在 iOS 7.0 中弃用 - 使用 NSForegroundColorAttributeName :)
                • 这确实是改变图标颜色的唯一解决方案
                • 抱歉@Atma,user3719695 在 6 月发布了另一个更简单的解决方案。
                • 为 [UITabBarItem 外观] 加 1 为我节省了一天,谢谢 :) 但是有什么方法我们不需要为标签栏按钮设置单个图像?
                • 完美解决我的问题
                【解决方案11】:

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

                【讨论】:

                • 在 iOS 9.1 中运行良好
                【解决方案12】:

                扩展@Sven Tiffe 对 iOS 7 的回答,您可以让您的代码自动为故事板中添加的未选择的 UITabBar 图像着色。以下方法将使您不必创建两组图标图像(即选中与未选中),并且不必以编程方式加载它们。将类别方法 imageWithColor:(参见 - How can I change image tintColor in iOS and WatchKit)添加到您的项目中,然后将以下内容放入您的项目中自定义 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 的类别(从 this answer 中提取):

                @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
                

                【讨论】:

                • 这是迄今为止完成任务最简单的方法,不知道为什么它没有被标记为接受的答案。
                • 就我而言,将上面的代码添加到 viewWillAppear 就可以了。 (在我的应用程序中调用 viewDidLoad 时按钮尚未加载,因此上面的代码仅在将文本颜色放置在 viewDidLoad 时更改文本颜色)。
                • 我觉得应该是item.image = [[item.image imageWithColor...]]。还包括imageWithColor 的代码将改善您的答案。
                • 这很好用。对于那些(像我一样)以前从未听说过类别的人,请使用:stackoverflow.com/questions/24324021/…rypress.com/tutorials/objective-c/categories
                • Thoughtbot 博客(robots.thoughtbot.com/designing-for-ios-blending-modes)上很好地讨论了在为您的应用程序设置主题的背景下(包括未选择的 UITabBarItem 图标)为现有图像着色,包括带有渐变的图像。这与此答案中使用的方法大致相同。可以确认它可以在 iOS8 上运行,并且可以轻松地移植到 Swift。
                【解决方案13】:

                SO 说我无法删除已接受的答案(我试过了),但显然,有很多 cmets 支持这不适用于 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
                

                【讨论】:

                • 这在 iOS 7 中不起作用。这是对我有用的 another solution
                • 对于 iOS 10。使用这个self.dashboardTabBar.unselectedItemTintColor = UIColor.black
                【解决方案14】:

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

                您可以像这样为选中和未选中的标签栏按钮设置色调:

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

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

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

                【讨论】:

                • 我得到了同样的结果。只有第一次。
                • 未选择的颜色有效,但选择后会切换回正常颜色,至少在 7.1 上。
                猜你喜欢
                • 1970-01-01
                • 2016-02-25
                • 2010-10-21
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-03-03
                相关资源
                最近更新 更多