[iOS SDK] Customizing text color of an UITabBarItem – the right way (iOS 7.0+)

After having a look at this good tutorial, i’ve noticed that some code has been declared deprecated in iOS 7.0+:

Old code (deprecated, but still works)

[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
 [UIColor whiteColor], UITextAttributeTextColor,
 nil] forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
 [UIColor redColor], UITextAttributeTextColor,
 nil] forState:UIControlStateHighlighted];

The most elegant solution for that is using NSForegroundColorAttributeName, and UIControlStateHighlighted.

iOS 7.0+ version of the previous code

 [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor blueColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];

It may seem too silly, but believe me, it wasn’t that easy to find the right solution between that many incorrect answers that still use UITextAttributeTextColor, which is deprecated.

Happy coding!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s