Is it possible to change UITabBarItem badge color
Solution 1
UITabBarItem
has this available since iOS 10.
var badgeColor: UIColor? { get set }
It's also available via appearence.
if #available(iOS 10, *) {
UITabBarItem.appearance().badgeColor = .green
}
reference docs: https://developer.apple.com/reference/uikit/uitabbaritem/1648567-badgecolor
Solution 2
Changing the badge-color is now natively supported in iOS 10 and later using the badgeColor
property inside your UITabBarItem
. See the apple docs for more infos on the property.
Example:
- Swift 3:
myTab.badgeColor = UIColor.blue
- Objective-C:
[myTab setBadgeColor:[UIColor blueColor]];
Solution 3
I wrote this piece of code for my app, but I have only tested it in iOS 7.
for (UIView* tabBarButton in self.tabBar.subviews) {
for (UIView* badgeView in tabBarButton.subviews) {
NSString* className = NSStringFromClass([badgeView class]);
// looking for _UIBadgeView
if ([className rangeOfString:@"BadgeView"].location != NSNotFound) {
for (UIView* badgeSubview in badgeView.subviews) {
NSString* className = NSStringFromClass([badgeSubview class]);
// looking for _UIBadgeBackground
if ([className rangeOfString:@"BadgeBackground"].location != NSNotFound) {
@try {
[badgeSubview setValue:[UIImage imageNamed:@"YourCustomImage.png"] forKey:@"image"];
}
@catch (NSException *exception) {}
}
if ([badgeSubview isKindOfClass:[UILabel class]]) {
((UILabel *)badgeSubview).textColor = [UIColor greenColor];
}
}
}
}
}
You're only able to update the badge background with an image, not a color. I have also exposed the badge label if you wanted to update that in some way.
Its important to note that this code must be called after setting the tabBarItem.badgeValue
!
EDIT: 4/14/14
The above code will work in iOS 7 when called anywhere. To get it working in iOS 7.1 call it in the view controllers -viewWillLayoutSubviews
.
EDIT: 12/22/14
Here's an updated snippet which I'm currently using. I put the code in a category extension for simplicity.
- (void)badgeViews:(void (^)(UIView* badgeView, UILabel* badgeLabel, UIView* badgeBackground))block {
if (block) {
for (UIView* tabBarButton in self.subviews) {
for (UIView* badgeView in tabBarButton.subviews) {
NSString* className = NSStringFromClass([badgeView class]);
if ([className rangeOfString:@"BadgeView"].location != NSNotFound) {
UILabel* badgeLabel;
UIView* badgeBackground;
for (UIView* badgeSubview in badgeView.subviews) {
NSString* className = NSStringFromClass([badgeSubview class]);
if ([badgeSubview isKindOfClass:[UILabel class]]) {
badgeLabel = (UILabel *)badgeSubview;
} else if ([className rangeOfString:@"BadgeBackground"].location != NSNotFound) {
badgeBackground = badgeSubview;
}
}
block(badgeView, badgeLabel, badgeBackground);
}
}
}
}
}
Then when you're ready to call it, it'll look like this.
[self.tabBar badgeViews:^(UIView *badgeView, UILabel *badgeLabel, UIView *badgeBackground) {
}];
EDIT: 11/16/15
It's been brought to my attention that some people need a little more clarity on what's happening in this code. The for loops are searching for a few views which are not publicly accessible. By checking if the views class name contains a part of the expected name, it's ensuring to reach the intended view while not setting off any possible red flags by Apple. Once everything has been located, a block is executed with easy access to these views.
It's noteworthy that the possibility exists for this code to stop working in a future iOS update. For example these internal views could one day acquire different class names. However the chances of that are next to none since even internally Apple rarely refactors classes to this nature. But even if they were to, it would be something along the title of UITabBarBadgeView
, which would still reach the expected point in code. Being that iOS9 is well out the door and this code is still working as intended, you can expect this problem to never arise.
Solution 4
I have the same problem and solved it by creating a little category that replace the BadgeView with an UILabel that you can customize easily.
https://github.com/enryold/UITabBarItem-CustomBadge/
Solution 5
For people using Swift, I managed to improve on TimWhiting answer in order to have the badge view working on any screen size and any orientation.
extension UITabBarController {
func setBadges(badgeValues: [Int]) {
for view in self.tabBar.subviews {
if view is CustomTabBadge {
view.removeFromSuperview()
}
}
for index in 0...badgeValues.count-1 {
if badgeValues[index] != 0 {
addBadge(index, value: badgeValues[index], color:UIColor(paletteItem: .Accent), font: UIFont(name: Constants.ThemeApp.regularFontName, size: 11)!)
}
}
}
func addBadge(index: Int, value: Int, color: UIColor, font: UIFont) {
let badgeView = CustomTabBadge()
badgeView.clipsToBounds = true
badgeView.textColor = UIColor.whiteColor()
badgeView.textAlignment = .Center
badgeView.font = font
badgeView.text = String(value)
badgeView.backgroundColor = color
badgeView.tag = index
tabBar.addSubview(badgeView)
self.positionBadges()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.positionBadges()
}
// Positioning
func positionBadges() {
var tabbarButtons = self.tabBar.subviews.filter { (view: UIView) -> Bool in
return view.userInteractionEnabled // only UITabBarButton are userInteractionEnabled
}
tabbarButtons = tabbarButtons.sort({ $0.frame.origin.x < $1.frame.origin.x })
for view in self.tabBar.subviews {
if view is CustomTabBadge {
let badgeView = view as! CustomTabBadge
self.positionBadge(badgeView, items:tabbarButtons, index: badgeView.tag)
}
}
}
func positionBadge(badgeView: UIView, items: [UIView], index: Int) {
let itemView = items[index]
let center = itemView.center
let xOffset: CGFloat = 12
let yOffset: CGFloat = -14
badgeView.frame.size = CGSizeMake(17, 17)
badgeView.center = CGPointMake(center.x + xOffset, center.y + yOffset)
badgeView.layer.cornerRadius = badgeView.bounds.width/2
tabBar.bringSubviewToFront(badgeView)
}
}
class CustomTabBadge: UILabel {}
1110
Updated on September 30, 2021Comments
-
1110 over 2 years
I want to change background color of
UITabBarItem
badge but can't find any resource on how to make it.
-
CrazyDeveloper about 10 yearsThe solution which is provided works in iOS 7 but not in iOS7.1. Can anything be done for 7.1?
-
cnotethegr8 about 10 yearsMake sure its called in your view controllers
-viewWillLayoutSubviews
. -
cnotethegr8 about 10 years@jeffamaphone the OP asked, 'is it possible'. Never did they request for an implementation that wont break. Your reasoning for giving me a down vote is inadequate. I ask you kindly to reverse the action.
-
Markus Rautopuro about 10 yearsWhen you refer to "view controller's
-viewWillLayoutSubviews
": which view controller are you talking about? The UITabBarController? -
Phillip almost 10 yearsWill this get rejected by Apple?
-
eold almost 10 yearsNo, i have an app online that uses this library.
-
Brock Boland over 9 yearsSuggestion: put the
if (block)
condition at the top of your method: without ablock
parameter, this method does nothing anyway. -
Brian Sachetta over 8 yearsPlease note: if you plan on using something like this in your production code, you should expect to be rejected by Apple's review process.
-
cnotethegr8 over 8 yearsWhat @BrianSachetta has said is completely false. My app still has this code and has not been rejected once. I don't understand why you gave me a down vote. The OP asked a question and I provided the answer. Maybe you're confused but on stackoverflow you don't down vote an answer because it's not in alignment with your coding beliefs. The voting system is intended for the use relative to the question / answer. Not for personal feelings.
-
Brian Sachetta over 8 yearsIt's not for personal feelings at all. Apple does not allow the use of private APIs in app store apps which is happening here. Sure they might not catch it but you still shouldn't do it.
-
cnotethegr8 over 8 years@BrianSachetta give one indication that the OP intended to release this code to the App Store. He never mentioned anything about the use of only public API's. And even if he had, my code is not using private API's. This is finding a specific subview from a public view. Which is completely acceptable with Apple. You are acting based on your personal feelings and not based on the OP's question. I will ask you to recognize your fault and undo your actions. The bottom line is the OP asked a question and I answered to the fullest of their question. You are trying to go beyond that, which is wrong.
-
Brian Sachetta over 8 yearsYou are using private API's as none of those subviews / classes are made available by Apple's documentation. If you feel I'm being too harsh by down voting due to something not specifically asked in the question, that's fine. But I'm not changing my vote until someone tells me I'm not allowed to down vote for that reason.
-
cnotethegr8 over 8 yearsHow about you read 'When should I vote down?' stackoverflow.com/help/privileges/vote-down and then explain to me how my answer was sloppy, no effort involved, or dangerously incorrect.
-
Brian Sachetta over 8 yearsYour answer is very thorough and you obviously put a lot of effort into it. However, using an undocumented API can lead to apps breaking out of nowhere, and more importantly, app store rejections. I'd call that dangerously incorrect.
-
cnotethegr8 over 8 yearsAgain, the OP never requested a solution for the App Store! You are trying to modify the original question to excuse your actions. You can pretend you care about rules but your contradictory actions for those of stackoverflows are obvious. The lack of the OPs requesting code for the App Store or the use of only 'Public APIs' makes this answer not fall into the category of 'dangerously incorrect'. At least lower your ego and be honest with yourself.
-
Brian Sachetta over 8 yearsThere's really no ego about it, man. People down vote things all the time - most of the time without even an explanation, sadly. I'm happy to remove the down vote if you mention in your post that the solution uses an undocumented API and is not guaranteed to work in the future / may not pass Apple's review process. That seems like a very fair compromise to me.
-
cnotethegr8 over 8 yearsI have no problem adding a note that it may break in the future, but I will not lie about it possibly not passing Apple's review process. Under no circumstances will this fail the review process.
-
Brian Sachetta over 8 yearsAgree to disagree on that last point but I will remove the downvote.
-
Avi over 8 yearsI'll throw in my unasked-for two cents. 1) Private views or view hierarchies are not private APIs. Apple has been making this distinction since forever. 2) Apple's guidelines are irrelevant to SO answers, unless the question clearly requires an answer acceptable to Apple. 3) It's a good idea to note that an answer may not be acceptable, but it's probably not worth a downvote. Simply leave a comment and move on.
-
Mantas Laurinavičius almost 8 yearsYou are accessing private property inside there. if([str isEqualToString:@"_UIBadgeView"] . How come Apple does not reject it? Did the permissions change?
-
eold over 7 yearsI've used it in one project few years ago, and Apple never reject it.
-
rjobidon over 7 yearsif ([myTab respondsToSelector:@selector(setBadgeColor:)]) { [myTab setBadgeColor:[UIColor blueColor]]; }
-
Jens over 6 yearsWhat happens when I still want to support iOS9? Do I need to enclose this in a
respondsToSelector
resp#available
call? -
Austin Berenyi over 6 yearsCan you explain how this is actually implemented? I'm a little confused.
-
Nuno Gonçalves about 3 yearsI just now realised I never answered this question @jens. This is probably no longer useful for this question per se, but might be for similar things. But If the api does not support the feature yet, you'll have to use other means in the "else". In this case use any other ways shown in these answers.
-
Jason Moore over 2 yearsNote that in addition to
normal
there are alsoselected
andfocused
states inUITabBarItemAppearance
.