在Swift中为一个tabBarItem设置tintColor

3

我将尝试为选项卡栏中的一个标签项设置tintColor。

目前,我的代码如下:

self.tabBar.tintColor = darkGrey
self.tabBar.unselectedItemTintColor = grey

我在我的选项卡中有5个tabBarItems(没有文本),当选择该项目时,我想将第一个设置为蓝色。

我该怎么做?

6个回答

3

您需要为每个tabBarItem单独设置它。 您可以通过在viewDidLoad()中放置此代码来更改特定选项卡的选项卡颜色。

//setting your tabBarItem to blue when selected
self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blue()], for:.selected)

嗯,如果你正在使用图像,我认为更容易的方法是更改资源颜色,而不是通过编程覆盖它们并呈现原始图像。 - Ace Rivera

3
如果你只想改变特定选项卡的色调,那么这就很有用了。
var tab1 : UITabBarItem = self.tabBar.items![0] as UITabBarItem
tab1.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.gray], for: .normal)

//For Image
tab1.image = UIImage(named: "imageName")!.withRenderingMode(.alwaysOriginal)

如果你不使用tab1,为什么要创建它? - KevinB
@Kevinb 显然他的意图是设置tab1.tintColor。 - Connor
我认为TabBarItem没有tintColor选项,但是TabBar有。 - Vini App

1
选择UITabbarItem并添加一个运行时属性'selectedImage',选择类型为'Image',将您的图像名称作为其值。

enter image description here

或者通过代码实现。
UITabBar *tabBar = self.tabBar;

UITabBarItem *targetTabBarItem = [[tabbar items] objectAtIndex:0]; // 
whichever tab-item
UIImage *selectedIcon = [UIImage imageNamed:@"name-of-selected-
image.png"];
[targetTabBarItem setSelectedImage:selectedIcon];

1

Here is the another way:

self.tabBar.tintColor = UIColor.red
let tabSelected = self.tabBar.selectedItem!
tabSelected.selectedImage = #imageLiteral(resourceName: "second")

1
你可以在storyboard中进行编辑
图像色调是所选图标的颜色
背景是选项卡栏的颜色
色调是图标的颜色


请查看下面的图片。

https://istack.dev59.com/7Jnwy.webp


我说过,我只想为一个选项卡栏目设置那个色调颜色。 - KevinB
不要生气 :) 试试这个。 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.barTintColor = UIColor.red } - dhin

0

我的原始代码

tabaritem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal)

我把alwaysOriginal改成了automatic,然后它就可以运行了

tabaritem.image = UIImage(named: imageName)?.withRenderingMode(.automatic)


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