是否可以为UITabBar上的每个按钮设置单独的色调颜色?

时间:2014-11-05 02:51:00

标签: ios objective-c cocoa-touch uitabbar

是否可以在标签栏上为单个UITabBarItem设置单独的色调?我只知道如何使用[UITabBar appearance] setTintColor:进行普遍设置。但是,例如,我希望一个标签在选中时用蓝色着色,另一个用红色等。

我知道通过将imageselectedImage属性设置为UIImageRenderingModeAlwaysOriginal来保留原始图像颜色可以部分缓解这一问题,但标题文本仍然具有整个标签的原始色调杆

4 个答案:

答案 0 :(得分:0)

更改tintColor属性是不可能的,但您仍然可以更改标签栏项目的文本颜色。

例如:

    [theTabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}
                                   forState:UIControlStateNormal];
    [theTabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor greenColor]}
                                   forState:UIControlStateHighlighted];

答案 1 :(得分:0)

改变个人色调并非不可能,只需要花费相当多的努力来实现。这样做的方法是覆盖标签栏的didSelectItem方法。当用户选择某个项目时,您将tabBar.tintColor更改为该项目所需的tintColor,然后必须致电selectedIndex = //The tapped index。如果你愿意,我会发布一些代码,它肯定是一个黑客

答案 2 :(得分:0)

实际上,您可以通过一些技巧来设置单个按钮的色调。

   let button1 = UITabBarItem(title: "Btn1", image: UIImage(systemName: "heart"), tag: 1)
   let button2 = UITabBarItem(title: "Btn2", image: UIImage(systemName: "heart"), tag: 2)
   let button3 = UITabBarItem(title: "Btn3", image: UIImage(systemName: "heart"), tag: 3)
   let button4 = UITabBarItem(title: "Btn4", image: UIImage(systemName: "heart"), tag: 4)
   let button5 = UITabBarItem(title: "Btn5", image: UIImage(systemName: "heart"), tag: 5)
   tabBar.items = [button1, button2, button3, button4, button5]

   // setting tint of the button4
   if let imageView = tabBar.subviews[4].subviews.first as? UIImageView {
      imageView.tintColor = UIColor.red 
      imageView.image = UIImage(systemName: "heart.fill")
   }

如果您还决定更改按钮的图像,请使用相同的imageView而不是button4.image,否则其他一些随机按钮可能会更改其色调。 tabBar.subviews [0]是栏本身的背景图像,后续的子视图是您添加的按钮。每个元素的类型都是UITabBarButton,它具有两个子视图:第一个UITabBarSwappableImageView和第二个UITabBarButtonLabel。

答案 3 :(得分:-1)

对于正常状态(未选中):

[tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}
                               forState:UIControlStateNormal];

选择状态:

[tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]}
                               forState:UIControlStateHighlighted];