-
-
Save mdabbagh88/23a97701ab95aabfd6288ac26d09a16d to your computer and use it in GitHub Desktop.
Badge number on a UIButton using MKNumberBadgeView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################ | |
### UIButton+BPBadgeButton.h ### | |
################################ | |
#import <UIKit/UIKit.h> | |
@interface UIButton (BPBadgeButton) | |
@property (nonatomic) NSUInteger badge; | |
@end | |
################################ | |
### UIButton+BPBadgeButton.h ### | |
################################ | |
#import "UIButton+BPBadgeButton.h" | |
#import "MKNumberBadgeView.h" | |
#import <objc/runtime.h> | |
static char const * const badgeKey = "badge"; | |
@interface UIButton () | |
-(MKNumberBadgeView *)badgeView; | |
@end | |
@implementation UIButton (BPBadgeButton) | |
-(void)setBadge:(NSUInteger)newBadge | |
{ | |
MKNumberBadgeView *badgeView = [self badgeView]; | |
badgeView.value = newBadge; | |
badgeView.frame = CGRectMake(self.frame.size.width-badgeView.badgeSize.width-10, | |
0, | |
badgeView.badgeSize.width+10, | |
self.frame.size.height); | |
badgeView.hidden = (newBadge == 0); | |
} | |
-(NSUInteger)badge | |
{ | |
MKNumberBadgeView *badgeView = [self badgeView]; | |
return badgeView.value; | |
} | |
-(MKNumberBadgeView *)badgeView; | |
{ | |
MKNumberBadgeView *badgeView = (MKNumberBadgeView *)objc_getAssociatedObject(self, badgeKey); | |
if(!badgeView){ | |
badgeView = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; | |
[self addSubview:badgeView]; | |
badgeView.hidden = YES; | |
objc_setAssociatedObject(self, badgeKey, badgeView, OBJC_ASSOCIATION_RETAIN); | |
} | |
return badgeView; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment