选项卡栏控制器中TabBar项目的不同颜色 [英] Different colors for TabBar items in Tab Bar Controller
问题描述
我有标签栏控制器,标签很少。
I have Tab Bar Controller with few tabs.
-
所有标签项应具有相同的非选择颜色的图像和文本。
All tab items should have same non-selected color for image and text.
所有标签项应具有不同的图像选择颜色和
文本。
All tab items should have different selected color for image and text.
我准备用选定和未选择项目所需的颜色创建图像。我知道如何为AppDelegate的所有标签更改此颜色
I am ready to create images with colors needed for selected and non-selected items. And I know how to change this colors for all tabs from AppDelegate
UITabBar.appearance().tintColor = UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)], for: UIControlState.selected)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.normal)
但我想制作不同的颜色对于不同的项目。
But I want to make different colors for different items.
推荐答案
在你的故事板中选择你的TabBarController并给它一个自定义类: TabBarController
在这个例子中:
In your Storyboard select your TabBarController and give it a custom class: TabBarController
in this example:
然后创建自定义TabBarController文件:
And then create the custom TabBarController file:
// Copyright © 2017 Erick Vavretchek. All rights reserved.
import UIKit
class TabBarController: UITabBarController {
enum tabBarMenu: Int {
case home
case list
case settings
}
// MARK: UITabBarController
override func viewDidLoad() {
super.viewDidLoad()
guard let tabBarMenuItem = tabBarMenu(rawValue: 0) else { return }
setTintColor(forMenuItem: tabBarMenuItem)
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard
let menuItemSelected = tabBar.items?.index(of: item),
let tabBarMenuItem = tabBarMenu(rawValue: menuItemSelected)
else { return }
setTintColor(forMenuItem: tabBarMenuItem)
}
// MARK: Private
private func setTintColor(forMenuItem tabBarMenuItem: tabBarMenu) {
switch tabBarMenuItem {
case .home:
viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.green
case .list:
viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
case .settings:
viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
}
}
}
在Assets.xcassets文件夹中选择用于TabBarItem的每个图像并将其设置为渲染为:模板图像
。这就是你可以简单地将它的tintColor更改为你喜欢的任何东西:
It is also important that in your Assets.xcassets folder you select the each image you are using for your TabBarItem and set them to Render As: Template Image
. That's how you can simply change its tintColor to whatever you like:
这篇关于选项卡栏控制器中TabBar项目的不同颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!