是否在加载视图之前设置UITabBarItem属性



我正在尝试更改UITabBar标题的颜色。

我在每个视图控制器的viewDidLoadS:中都有这个代码

[self.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : 
[UIColor whiteColor]} forState:UIControlStateSelected];
[self.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : 
[UIColor whiteColor]} forState:UIControlStateNormal];

只有在加载视图后(因此,在选项卡栏项目至少点击一次后),颜色才会从默认值更改,这只起到一半的作用。这不是我想要的行为,我希望在应用程序启动后尽快设置颜色。

将代码放在视图控制器的initWithNibName:中根本不起作用。

有什么方法可以从应用程序代表的didFinishLaunchingWithOptions中寻址tabBarItem吗?

更新:

我在下面标记为正确的答案是有效的,尽管我也找到了另一种方法,如果你想解决单个UITabBarItems的问题,这种方法效果更好。在选项卡栏控制器中,通过从界面生成器创建出口或以编程方式将选项卡栏分配给指针后,您可以这样处理单个tabBarItem(对于tabBar指向的UITabBar):

UITabBarItem *tab1 = [self.tabBar.items objectAtIndex: 0];
UITabBarItem *tab2 = [self.tabBar.items objectAtIndex: 1];

等等。。。

然后你可以做之类的事情

[tab1 setTitleTextAttributes:]

以及其他各种各样的东西。

查看UIAppearance。https://developer.apple.com/library/iOS/documentation/UIKit/Reference/UIAppearance_Protocol/Reference/Reference.html

为选项卡和导航栏创建所需外观的实用程序类。然后从App Delegate的didFinishLaunchingWithOptions调用该类。下面是一个让你开始的例子:

+ (void) setUpTabBarAppearance
{
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Your Font" size:15], UITextAttributeFont, [UIColor whiteColor], UITextAttributeTextColor, [UIColor clearColor], UITextAttributeTextShadowColor, nil] forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:@{ UITextAttributeTextColor : [UIColor greenColor] }forState:UIControlStateSelected];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
}

然后,从应用程序代理的didFinishLaunchingWithOptions中,调用:[实用程序设置选项卡外观];此外,通过这种方式,您只需要修改TabBar的外观一次,而不是在每个类中。

我的AppDelegate didFinishLaunchingWithOptions:中有以下内容

[[UITabBar appearance] setTintColor:[UIColor yellowColor]];
[[UITabBar appearance] setBarTintColor:[UIColor darkGrayColor]];
[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:10.0f], NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateSelected];

最新更新