更改标签栏项目图像和文本颜色 iOS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31117069/
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
Changing tab bar item image and text color iOS
提问by Greg Peckory
Here is my tab bar:
这是我的标签栏:
The following image shows the program being run and the "NEWS" item selected:
下图显示了正在运行的程序和选择的“新闻”项目:
It is clear the bar tint color is working fine as I want !
很明显,条形色调可以正常工作!
But the tintColor only affects the image and not the text.
但是 tintColor 只影响图像而不影响文本。
Also, when the an item is selected (as seen above, news) the item color goes blue! How do I prevent this from happening? I want it to stay white.
此外,当一个项目被选中(如上所示,新闻)项目颜色变为蓝色!我如何防止这种情况发生?我想让它保持白色。
Why is the text changing to a white color when selected but not when it is unselected?
为什么选中时文本会变为白色,而未选中时则不会?
I basically want the item color and text color to be white all the time.
我基本上希望项目颜色和文本颜色始终为白色。
How do I achieve this? Thanks for any help.
我如何实现这一目标?谢谢你的帮助。
Does it require swift code for each individual item?
每个单独的项目都需要快速代码吗?
EDIT:
编辑:
回答by Kingofmit
From UITabBarItem class docs:
来自 UITabBarItem 类文档:
By default, the actual unselected and selected images are automatically created from the alpha values in the source images. To prevent system coloring, provide images with UIImageRenderingModeAlwaysOriginal.
默认情况下,实际未选择和已选择的图像是根据源图像中的 alpha 值自动创建的。为防止系统着色,请使用 UIImageRenderingModeAlwaysOriginal 提供图像。
The clue is not whether you use UIImageRenderingModeAlwaysOriginal, the important thing is when to use it.
线索不在于你是否使用 UIImageRenderingModeAlwaysOriginal,重要的是何时使用它。
To prevent the grey color for unselected items, you will just need to prevent the system colouring for the unselected image. Here is how to do this:
为了防止未选中项目的灰色,您只需要防止未选中图像的系统着色。以下是如何执行此操作:
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
As you can see, I asked iOS to apply the original color (white, yellow, red, whatever) of the image ONLY for the UNSELECTED state, and leave the image as it is for the SELECTED state.
如您所见,我要求 iOS 仅将图像的原始颜色(白色、黄色、红色等)应用于 UNSELECTED 状态,而将图像保留为 SELECTED 状态。
Also, you may need to add a tint color for the tab bar in order to apply a different color for the SELECTED state (instead of the default iOS blue color). As per your screenshot above, you are applying white color for the selected state:
此外,您可能需要为选项卡栏添加色调,以便为 SELECTED 状态应用不同的颜色(而不是默认的 iOS 蓝色)。根据上面的屏幕截图,您正在为所选状态应用白色:
self.tabBar.tintColor = UIColor.whiteColor()
EDIT:
编辑:
回答by AMarones
Swift 3
斯威夫特 3
I did it by creating a custom tabbar controller and added this code inside the viewDidLoad
method.
我通过创建自定义标签栏控制器并在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)
It worked for me!
它对我有用!
回答by Rajesh Loganathan
Swift
迅速
For Image:
对于图像:
custom.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tab_icon_normal"), selectedImage: UIImage(named: "tab_icon_seelcted"))
For Text:
对于文本:
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.grayColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState:.Selected)
回答by Vasil Garov
Swift 4.2 and Xcode 10
Swift 4.2 和 Xcode 10
The solution that worked for me:
对我有用的解决方案:
- Image setup- from the storyboard set Bar Item Image and Selected Image. To remove the tint overlay on the images go to Assets catalog, select the image and change its rendering mode like this:
- 图像设置- 从情节提要中设置 Bar Item Image 和 Selected Image。要移除图像上的色调叠加,请转到资产目录,选择图像并更改其渲染模式,如下所示:
This will prevent the Tab bar component from setting its default image tint.
这将阻止标签栏组件设置其默认图像色调。
Text- here I created a simple UITabBarController subclass and in its viewDidLoad method I customized the default and selected text color like this:
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) } }
文本- 在这里我创建了一个简单的 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) } }
Just set this class as your Tab bar controller custom class in identity inspector in IB.
只需在 IB 的身份检查器中将此类设置为您的 Tab bar 控制器自定义类。
Voila! That's it.
瞧!就是这样。
iOS 13 Update:
iOS 13 更新:
Add this to your setup for iOS 13:
将此添加到您的 iOS 13 设置中:
if #available(iOS 13, *) {
let appearance = UITabBarAppearance()
appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: .red]
tabBar.standardAppearance = appearance
}
回答by Bartosz Olszanowski
Swift 3
斯威夫特 3
This worked for me (referring to set tabBarItems image colors):
这对我有用(指的是设置 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
}
}
I have noticed that if you set image with rendering mode = .alwaysOriginal, the UITabBar.tintColor doesn't have any effect.
我注意到,如果您使用渲染模式 = .alwaysOriginal 设置图像,则 UITabBar.tintColor 没有任何效果。
回答by Andreas
Swift 3
斯威夫特 3
First of all, make sure you have added the BOOLEAN key "View controller-based status bar appearance" to Info.plist, and set the value to "NO".
首先,确保您已将 BOOLEAN 键“View controller-based status bar appearance”添加到 Info.plist,并将值设置为“NO”。
Appdelegate.swift
Appdelegate.swift
Insert code somewhere after "launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {"
在“launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {”之后的某处插入代码
- Change the color of the tab bar itself with RGB color value:
- 使用 RGB 颜色值更改标签栏本身的颜色:
UITabBar.appearance().barTintColor = UIColor(red: 0.145, green: 0.592, blue: 0.804, alpha: 1.00)
UITabBar.appearance().barTintColor = UIColor(red: 0.145, green: 0.592, blue: 0.804, alpha: 1.00)
OR one of the default UI colors:
或默认 UI 颜色之一:
UITabBar.appearance().barTintColor = UIColor.white)
UITabBar.appearance().barTintColor = UIColor.white)
- Change the text color of the tab items:
- 更改选项卡项的文本颜色:
The selected item
所选项目
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)
The inactive items
非活动项目
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black], for: .normal)
- To change the color of the image, I believe the easiest approach is to make to separate images, one for each state.
- 要更改图像的颜色,我认为最简单的方法是制作单独的图像,每个状态一个。
If you don′t make the icons from scratch, alternating black and white versions are relatively easy to make in Photoshop.
如果您不是从头开始制作图标,那么在 Photoshop 中制作交替的黑白版本相对容易。
Adobe Photoshop (almost any version will do)
Adobe Photoshop(几乎任何版本都可以)
Make sure your icon image has transparent background, and the icon itself is solid black (or close).
确保您的图标图像具有透明背景,并且图标本身是纯黑色(或关闭)。
Open the image file, save it under a different file name (e.g. exampleFilename-Inverted.png)
打开图像文件,将其保存在不同的文件名下(例如 exampleFilename-Inverted.png)
In the "Adjustments" submenu on the "Image" menu:
在“图像”菜单上的“调整”子菜单中:
Click "Invert"
点击“反转”
You now have a negative of your original icon.
您现在拥有原始图标的底片。
In XCode, set one of the images as "Selected Image" under the Tab Bar Properties in your storyboard, and specify the "inactive" version under "Bar Item" image.
在 XCode 中,在情节提要的 Tab Bar Properties 下将其中一张图像设置为“Selected Image”,并在“Bar Item”图像下指定“inactive”版本。
Ta-Da
打打
回答by Mixon McLaren
Swift 4: In your UITabBarController change it by this code
Swift 4:在您的 UITabBarController 中通过此代码更改它
tabBar.unselectedItemTintColor = .black
回答by Fred Sousa
Try add it on AppDelegate.swift(inside applicationmethod):
尝试将其添加到AppDelegate.swift(在应用程序方法中):
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)
Example:
例子:
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
}
Example:
例子:
My english is so bad! I'm sorry! :-)
我的英语太差了!抱歉!:-)
回答by kuzdu
I know here are lots of answers but I can't find an easy and valid copy/paste answer for Swift 4.2/ Swift 5.1
我知道这里有很多答案,但我找不到Swift 4.2/Swift 5.1的简单有效的复制/粘贴答案
tabBarController?.tabBar.tintColor = UIColor.red
tabBarController?.tabBar.unselectedItemTintColor = UIColor.green
Or use UITabBarItem.appearance()
instead of tabBarController?.tabBar
或者使用UITabBarItem.appearance()
代替tabBarController?.tabBar
Images have to be UIImageRenderingModeAlwaysTemplate
回答by Amol Pokale
Swift 3.0
斯威夫特 3.0
I created the tabbar class file and wrote the following code
我创建了标签栏类文件并编写了以下代码
In viewDidLoad
:
在viewDidLoad
:
self.tabBar.barTintColor = UIColor.white
self.tabBar.isTranslucent = true
let selectedColor = UIColor.red
let unselectedColor = UIColor.cyan
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: unselectedColor,NSFontAttributeName: UIFont(name: "Gotham-Book", size: 10)!], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedColor,NSFontAttributeName: UIFont(name: "Gotham-Book", size: 10)!], for: .selected)
if let items = self.tabBar.items {
for item in items {
if let image = item.image {
item.image = image.withRenderingMode( .alwaysOriginal )
item.selectedImage = UIImage(named: "(Imagename)-a")?.withRenderingMode(.alwaysOriginal)
}
}
}
After viewDidLoad
:
之后viewDidLoad
:
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if(item.title! == "title")
{
item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)
}
if(item.title! == "title")
{
item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)
}
if(item.title! == "title")
{
item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)
}
if(item.title! == "title")
{
item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)
}
if(item.title! == "title")
{
item.selectedImage = UIImage(named: "(Imagname)-a")?.withRenderingMode(.alwaysOriginal)
}
}
in view did load method you have to set the selected image and other image are showing with RenderingMode and in tab bar delegate methods you set the selected image as per title
在视图确实加载方法中,您必须设置所选图像,其他图像使用 RenderingMode 显示,在选项卡栏委托方法中,您根据标题设置所选图像