改变iOS选项卡栏项目图片和文字颜色

84
这是我的选项卡栏: enter image description here 下图显示了程序运行时选择了“NEWS”项目: enter image description here 显然,“bar tint color”的效果很好!
但是,“tintColor”仅影响图像,而不影响文本。
此外,当选择某个项目时(如上图中的新闻),该项目颜色变为蓝色!我该如何防止这种情况发生?我希望它保持白色。
为什么在选择项目时文本会变成白色,而在未选择时则不会呢?
基本上,我希望项目颜色和文本颜色始终为白色。
我该如何实现这一点?感谢任何帮助。
是否需要Swift代码来处理每个条目?
编辑: enter image description here

你能为所有图标创建白色和灰色的图片,并在需要时进行更改吗? - Max
当选中图片时图片会变蓝,未被选中的文本是白色。我不知道为什么......这是我的问题。 - Greg Peckory
25个回答

98

来自UITabBarItem类文档:

默认情况下,未选中和选中的实际图像是从源图像中的alpha值自动创建的。为了防止系统着色,请提供带有UIImageRenderingModeAlwaysOriginal属性的图像。

关键不在于是否使用UIImageRenderingModeAlwaysOriginal,而在于何时使用它。

为了防止未选定项目变灰色,您只需要防止系统对未选定图像进行着色。以下是如何实现:

var firstViewController:UIViewController = UIViewController()
// The following statement is what you need
var customTabBarItem:UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "YOUR_IMAGE_NAME")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "YOUR_IMAGE_NAME"))
firstViewController.tabBarItem = customTabBarItem

正如您所看到的,我要求iOS仅在未选定状态下应用图像的原始颜色(白色、黄色、红色等),并将图像保留为选定状态。

此外,您可能需要为选项卡栏添加一个着色颜色以应用不同于默认iOS蓝色的颜色于选定状态。根据您上面的截图,您正在为选定状态应用白色:

self.tabBar.tintColor = UIColor.whiteColor()

编辑:

在此输入图片描述


我需要创建一个与选项卡栏相对应的类来输入这段代码吗? - Greg Peckory
我已经设置了上面的tintColor,如您所见。此外,我已将渲染设置为原始图像,请参见编辑。 - Greg Peckory
我应该把代码 firstViewController.tabBarItem = customTabBarItem 放在哪里? - Greg Peckory
@GregoryPeck 你必须将它放在TabBarClass中。 - Kingofmit
2
抱歉问了这么多问题,但我不确定如何创建选项卡栏类。例如- TabBarClass: ??, ??,我似乎无法将其与我的选项卡栏连接起来。我必须将其连接到选项卡栏还是选项卡栏控制器? - Greg Peckory
显示剩余4条评论

79

Swift 3

我通过创建一个自定义的选项卡控制器并在viewDidLoad方法中添加了以下代码来实现。

    if let count = self.tabBar.items?.count {
        for i in 0...(count-1) {
            let imageNameForSelectedState   = arrayOfImageNameForSelectedState[i]
            let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]

            self.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState)?.withRenderingMode(.alwaysOriginal)
            self.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState)?.withRenderingMode(.alwaysOriginal)
        }
    }

    let selectedColor   = UIColor(red: 246.0/255.0, green: 155.0/255.0, blue: 13.0/255.0, alpha: 1.0)
    let unselectedColor = UIColor(red: 16.0/255.0, green: 224.0/255.0, blue: 223.0/255.0, alpha: 1.0)

    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: unselectedColor], for: .normal)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedColor], for: .selected)

它对我起作用了!

在此处输入图像描述


1
在Swift 4中,“NSForegroundColorAttributeName”已更名为“NSAttributedStringKey.foregroundColor”。 - Alienbash
在Swift4.2中,“NSAttributedStringKey”已被重命名为“NSAttributedString.Key”。 - XLE_22

59

Swift


对于图片:

custom.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tab_icon_normal"), selectedImage: UIImage(named: "tab_icon_selected"))

翻译内容:

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
    
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)

55

Swift 5 和 Xcode 13

对我起作用的解决方案:

  1. 图像设置 - 从故事板中设置 Bar Item 图像和选定图像。要删除图像上的色调叠加效果,请转到资产目录,选择图像并更改其渲染模式,如下所示:

image render mode

这将防止 Tab 栏组件设置其默认图像色调。

  1. 文本 - 在此处,我创建了一个简单的 UITabBarController 子类,并在它的 viewDidLoad 方法中自定义了默认和选定的文本颜色,如下所示:

     class HomeTabBarController: UITabBarController {
         override func viewDidLoad() {
             super.viewDidLoad()
    
             let appearance = UITabBarItem.appearance(whenContainedInInstancesOf: [HomeTabBarController.self])
             appearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: .black], for: .normal)
             appearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: .red], for: .selected)
         }
     }
    

只需在IB中的身份检查器中将此类设置为标签栏控制器的自定义类即可。

就这样,完成了。

iOS 13 更新:

+ iOS 15 / Xcode 13 更新:

将以下内容添加到iOS 13和iOS 15的设置中:

更新23/09/2022:针对在使用Xcode 13构建时iOS 15上出现标签栏丢失的奇怪行为进行更新。

if #available(iOS 13, *) {
    let appearance = UITabBarAppearance()
    appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: .red]
    tabBar.standardAppearance = appearance
    // Update for iOS 15, Xcode 13
    if #available(iOS 15.0, *) {
        tabBar.scrollEdgeAppearance = appearance
    }
}

1
如果您想使用检查器完成此操作,这应该是被接受的答案!非常感谢,这解决了我的问题。 - Emanuel Amiguinho
谢谢,你的iOS 13更新真的帮了我。我遇到了一个奇怪的bug,当tabbar最初创建时,所选项目的文本颜色是正确的,但在tabbar隐藏并重新出现后(例如呈现全屏模态然后解除),更改选项卡会将所选项目的文本颜色重置为色调颜色。添加iOS 13设置解决了这个问题。 - Saul
更改渲染模式对我有用。 - undefined

20

Swift 4: 在您的UITabBarController中,请使用以下代码进行更改

tabBar.unselectedItemTintColor = .black

Objective-C self.tabBar.unselectedItemTintColor = [UIColor colorNamed:@"ColorName"];Objective-C self.tabBar.unselectedItemTintColor = [UIColor colorNamed:@"ColorName"]; - undefined

17

Swift 3

这对我有效(指设置 tabBarItems 图片颜色):

UITabBar.appearance().tintColor = ThemeColor.Blue

if let items = tabBarController.tabBar.items {
        let tabBarImages = getTabBarImages() // tabBarImages: [UIImage]
        for i in 0..<items.count {
            let tabBarItem = items[i]
            let tabBarImage = tabBarImages[i]
            tabBarItem.image = tabBarImage.withRenderingMode(.alwaysOriginal)
            tabBarItem.selectedImage = tabBarImage
        }
    }

我注意到,如果你使用渲染模式 = .alwaysOriginal来设置图像,UITabBar.tintColor不会产生任何效果。


17

我知道这里有很多答案,但我找不到一个简单有效的复制/粘贴答案适用于Swift 4.2/Swift 5.1

tabBarController?.tabBar.tintColor = UIColor.red
tabBarController?.tabBar.unselectedItemTintColor = UIColor.green

或者使用UITabBar.appearances()代替tabBarController?.tabBar,像这样:

UITabBar.appearance().tintColor = UIColor.red
UITabBar.appearance().unselectedItemTintColor = UIColor.green

图片必须是UIImageRenderingModeAlwaysTemplate


终于有一个简单的解决方案了! - Chris
1
外观(而不是外观) - Void Asif

12

Swift 3

首先,确保您已将BOOLEAN键“View controller-based status bar appearance”添加到Info.plist中,并将值设置为“NO”。

Appdelegate.swift

在“launchOptions:[UIApplicationLaunchOptionsKey:Any]?) - > Bool {”之后的某个位置插入代码:

  1. 使用RGB颜色值更改选项卡栏本身的颜色:

UITabBar.appearance().barTintColor = UIColor(red: 0.145, green: 0.592, blue: 0.804, alpha: 1.00)

或使用其中一个默认的UI颜色:

UITabBar.appearance().barTintColor = UIColor.white)


  1. 更改选项卡项的文本颜色:

所选项目

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)

未激活的项目

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black], for: .normal)

  1. 要更改图像的颜色,我认为最简单的方法是制作两个单独的图像,每个状态一个。

如果您不从头开始制作图标,则在Photoshop中交替使用黑色和白色版本相对容易。


Adobe Photoshop(几乎任何版本都可以)

确保您的图标图像具有透明背景,并且图标本身是纯黑色(或接近纯黑色)。

打开图像文件,将其另存为不同的文件名(例如exampleFilename-Inverted.png)

在“图像”菜单的“调整”子菜单中:

点击“反转”

现在您拥有原始图标的负片。

在XCode中,您需要在故事板中的选项卡栏属性下设置一个图像作为“选中图像”,并在“Bar Item”图像下指定“非活动”版本。

完成啦!


对于您的第三点,您可以不使用Photoshop进行更改,而是使用以下代码:UITabBar.appearance().tintColor = UIColor.black - Chaudhry Talha
@ChaudhryTalha,tintcolor 适用于选定状态的 tabbar 图标。但是对于未选定状态的图标颜色(在 iOS10 以下),是否有类似的属性可以更改? - anoo_radha

10

尝试将它添加到AppDelegate.swift中(在application方法内):

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

// For WHITE color: 
UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)

例子:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Tab bar icon selected color
    UITabBar.appearance().tintColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
    // For WHITE color: UITabBar.appearance().tintColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
    return true
}

示例:

输入图像描述

输入图像描述

我的英语太烂了!抱歉!:-)


5
在Swift 5 ioS 13.2中,TabBar的样式发生了变化,以下代码经过测试可以100%正常工作。
请在您的UITabBarController类中添加以下代码。
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let appearance = UITabBarAppearance()
        appearance.backgroundColor = .white

        setTabBarItemColors(appearance.stackedLayoutAppearance)
        setTabBarItemColors(appearance.inlineLayoutAppearance)
        setTabBarItemColors(appearance.compactInlineLayoutAppearance)

        setTabBarItemBadgeAppearance(appearance.stackedLayoutAppearance)
        setTabBarItemBadgeAppearance(appearance.inlineLayoutAppearance)
        setTabBarItemBadgeAppearance(appearance.compactInlineLayoutAppearance)

        tabBar.standardAppearance = appearance
 }

@available(iOS 13.0, *)
private func setTabBarItemColors(_ itemAppearance: UITabBarItemAppearance) {
    itemAppearance.normal.iconColor = .lightGray
    itemAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.gray]

    itemAppearance.selected.iconColor = .white
    itemAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange]
}

@available(iOS 13.0, *)
private func setTabBarItemBadgeAppearance(_ itemAppearance: UITabBarItemAppearance) {
    //Adjust the badge position as well as set its color
    itemAppearance.normal.badgeBackgroundColor = .orange
    itemAppearance.normal.badgeTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    itemAppearance.normal.badgePositionAdjustment = UIOffset(horizontal: 1, vertical: -1)
}

1
我尝试了您的方法,但在iOS 15上并没有生效。我无法改变应用的徽章颜色或属性。您解决了这个问题吗? - Thao Tran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接