ios 未选择的 UITabBar 颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11512783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unselected UITabBar color?
提问by user1530090
I have an UITabBar with 5 items. I want to change the unselected color of all items. The items aren't declared in the UIViewController classes (i built them and linked the views in the Storyboard).
我有一个包含 5 个项目的 UITabBar。我想更改所有项目的未选择颜色。这些项目没有在 UIViewController 类中声明(我构建了它们并链接了 Storyboard 中的视图)。
Is there an code like this : [[UITabBar appearance] set***UN***SelectedImageTintColor:[UIColor whiteColor]];
?
有没有这样的代码:[[UITabBar appearance] set***UN***SelectedImageTintColor:[UIColor whiteColor]];
?
采纳答案by john.k.doe
SO says i cannot delete the accepted answer (i tried), but obviously, there are a lot of upvotes for comments that this doesn't work for iOS 7.
所以说我不能删除接受的答案(我试过),但显然,有很多评论认为这不适用于 iOS 7。
See the other answer below with many more upvotes, or the link in @Liam's comment to this answer.
请参阅下面的其他答案以及更多赞成票,或@Liam 对此答案的评论中的链接。
for iOS 6 only
仅适用于 iOS 6
It should be as simple as this:
它应该像这样简单:
[[UITabBar appearance] setTintColor:[UIColor grayColor]]; // for unselected items that are gray
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]]; // for selected items that are green
回答by Sven Tiffe
This will not work under iOS 7 as far as I can say. In particular, tintColorof the tab bar will define the color of the selected tab, not of the unselected ones. If you want to change the default in iOS 7, it seems that you have to actually use different icons (in the color you like to have for unselected tabs) and set the color of the text.
据我所知,这在 iOS 7 下是行不通的。特别是,选项卡栏的tintColor将定义所选选项卡的颜色,而不是未选择的选项卡的颜色。如果您想更改 iOS 7 中的默认值,似乎您必须实际使用不同的图标(使用您喜欢的未选择选项卡的颜色)并设置文本的颜色。
This example should tint selected tabs to red and render others in green. Run this code in your TabBarController:
此示例应将选定的选项卡着色为红色,并将其他选项卡呈现为绿色。在 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"];
If you set the icon in the story board only, you can control the color of the selected tab only (tintColor). All other icons and corresponding text will be drawn in gray.
如果仅在故事板中设置图标,则只能控制所选选项卡的颜色 (tintColor)。所有其他图标和相应的文本将以灰色绘制。
Maybe someone knows an easier way to adopt the colors under iOS 7?
也许有人知道在 iOS 7 下采用颜色的更简单方法?
回答by vtcajones
In iOS 10 and higher, there are 3 possible easy solutions:
在iOS 10 及更高版本中,有 3 种可能的简单解决方案:
A. Instance from code (Swift):
A. 代码实例(Swift):
self.tabBar.unselectedItemTintColor = unselectedcolor
B. Instance from IB:
B. 来自 IB 的实例:
Add a Key Path: unselectedItemTintColor
of type: Color
添加一个 Key Path:unselectedItemTintColor
类型:Color
C. Global appearance (Swift):
C. 全球亮相(Swift):
UITabBar.appearance().unselectedItemTintColor = unselectedcolor
回答by Kpalser
Extending @Sven Tiffe's answer for iOS 7, you can get your code to automatically tint the unselected UITabBar images added in the storyboard. The following approach will save you having to create two sets of icon images (i.e. selected vs unselected) and having to programatically load them in. Add the category method imageWithColor: (see - How can I change image tintColor in iOS and WatchKit) to your project then put the following in your custom UITabBarController viewDidLoad method:
扩展 @Sven Tiffe 对 iOS 7 的回答,您可以让您的代码自动为故事板中添加的未选择的 UITabBar 图像着色。以下方法将使您不必创建两组图标图像(即选中的与未选中的)并以编程方式加载它们。将类别方法 imageWithColor:(请参阅 -如何在 iOS 和 WatchKit 中更改图像 tintColor)添加到您的项目然后将以下内容放入您的自定义 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];
}
Create a Category called UIImage+Overlay and on UIImage+Overlay.m (extracted from this answer) :
在 UIImage+Overlay.m 上创建一个名为 UIImage+Overlay 的类别(从这个答案中提取 ):
@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
回答by Abhishek Jain
Swift version in iOS 10 and higher -
iOS 10 及更高版本中的 Swift 版本 -
UITabBar.appearance().tintColor = UIColor.gray
UITabBar.appearance().unselectedItemTintColor = UIColor.gray
回答by JoeGalind
Translating user3719695's answer to Swift, which now uses extensions:
翻译 user3719695 对 Swift 的回答,现在使用扩展:
UIImage+Overlay.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
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)
}
}
回答by kgaidis
I had to move the code into viewWillAppear
because in viewDidLoad
the images weren't set yet.
我不得不将代码移入,viewWillAppear
因为viewDidLoad
图像尚未设置。
Swift 4 Translation
斯威夫特 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)
}
}
回答by Anchor
The new answer to do this programmatically as of iOS 10+ is to use the unselectedItemTintColor
API. For example, if you have initialized your tab bar controller inside your AppDelegate
, it would looks like the following:
从 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
...
}
回答by AhmedZah
Swift 4 version (Without implicitly unwrapping Optionals) :
UIImage+Overlay.swift
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
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)
}
}
回答by shokuroff
Or just without coding. Swift 4, Xcode 10.1.
或者只是没有编码。斯威夫特 4,Xcode 10.1。
- Add
UITabBar
on your View Controller using Interface Builder. - Select the added view in the left panel.
- Type
cmd + alt + 3
or just clickShow the Identity Inspector
in the right panel. - In section
User Defined Runtime Attributes
click on plusbutton to add a new attribute and call it asunselectedItemTintColor
(see here). - Without leaving the section from the previous step (see number 4) under
Type
column chooseColor
type. - Finally, set the necessary color under
Value
section. - Compile your project
- Over. Congratulations.
UITabBar
使用Interface Builder添加您的视图控制器。- 在左侧面板中选择添加的视图。
- 在右侧面板中键入
cmd + alt + 3
或单击即可Show the Identity Inspector
。 - 在部分中
User Defined Runtime Attributes
单击加号按钮以添加新属性并将其命名为unselectedItemTintColor
(请参阅此处)。 - 不离开上一步中的部分(参见数字 4),在
Type
列选择Color
类型下。 - 最后,在
Value
部分下设置必要的颜色。 - 编译你的项目
- 超过。恭喜。