Skip to content

Instantly share code, notes, and snippets.

@YK-Unit
Last active August 29, 2015 14:02
Show Gist options
  • Save YK-Unit/7e44b5dec2f654b08012 to your computer and use it in GitHub Desktop.
Save YK-Unit/7e44b5dec2f654b08012 to your computer and use it in GitHub Desktop.
[UIButton+BadgeValue]—UIButton's Category to enable UIButton to set badgeValue like UITabBarItem.
#import <UIKit/UIKit.h>
@interface UIButton (BadgeValue)
- (void)setBadgeValue:(NSString *)value;
@end
#import "UIButton+BadgeValue.h"
@implementation UIButton (BadgeValue)
- (void)setBadgeValue:(NSString *)value
{
static UILabel *lb_badgeValue = nil;
if (value) {
if (!lb_badgeValue) {
lb_badgeValue = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width/2, 0, self.frame.size.width/2, self.frame.size.height/2)];
lb_badgeValue.textAlignment = NSTextAlignmentCenter;
lb_badgeValue.textColor = [UIColor whiteColor];
lb_badgeValue.backgroundColor = [UIColor redColor];
lb_badgeValue.layer.masksToBounds = YES;
lb_badgeValue.layer.cornerRadius = self.frame.size.width/4;
[self addSubview:lb_badgeValue];
}
NSInteger frontSize = 14;
NSInteger length = [value length];
switch (length) {
case 1:
frontSize = 14;
break;
case 2:
frontSize = 12;
break;
case 3:
frontSize = 8;
break;
default:
frontSize = 10;
break;
}
lb_badgeValue.font = [UIFont systemFontOfSize:frontSize];
lb_badgeValue.text = value;
}else{
if (lb_badgeValue) {
[lb_badgeValue removeFromSuperview];
lb_badgeValue = nil;
}
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment