未选择的UITabBar颜色?

时间:2012-07-16 21:24:05

标签: ios uitabbar

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

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

14 个答案:

答案 0 :(得分: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下采用颜色的更简单方法吗?

答案 1 :(得分:72)

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

一个。代码实例(Swift):

self.tabBar.unselectedItemTintColor = unselectedcolor

B中。来自IB的实例:

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

℃。全球亮相(斯威夫特):

UITabBar.appearance().unselectedItemTintColor = unselectedcolor

答案 2 :(得分:69)

扩展@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的类别和UIImage + Overlay.m(从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

答案 3 :(得分:19)

所以我说我不能删除已接受的答案(我试过),但显然,有很多评论的赞成,这对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

答案 4 :(得分:17)

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

答案 5 :(得分:14)

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

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

答案 6 :(得分: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 :(得分:3)

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
    }

答案 8 :(得分:1)

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

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

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

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

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

答案 9 :(得分:1)

从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

        ...
    }

答案 10 :(得分: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)
    }
}

答案 11 :(得分:0)

@ JoeGalid与Xamarin的imageWithColor:解决方案:

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)

答案 12 :(得分:0)

或者只是无需编码 Swift 4 Xcode 10.1

  1. 使用 Interface Builder 在您的View Controller中添加UITabBar
  2. 在左侧面板中选择添加的视图。
  3. 键入cmd + alt + 3或只需单击右侧面板中的Show the Identity Inspector
  4. User Defined Runtime Attributes部分中,单击按钮以添加新属性,并将其称为unselectedItemTintColor(请参见here)。
  5. Type列下的上一步步骤(请参见数字4)中选择[{1}}类型。
  6. 最后,在Color部分下设置必要的颜色。
  7. 编译项​​目
  8. 结束。恭喜你

enter image description here

答案 13 :(得分:0)

使用Swift快速选择标签栏的颜色

  1. 获取您的TabBarViewController的引用
  2. 使用以下代码。

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

希望这会有所帮助。