項(xiàng)目需求需要在導(dǎo)航欄按鈕上顯示小紅點(diǎn)礁叔,但按鈕使用的是系統(tǒng)原生的UIBarbuttonItem,重寫控件不太可能,于是利用category的方式為其添加紅點(diǎn)并顯示迄薄。
具體實(shí)現(xiàn)是利用關(guān)聯(lián)琅关,首先需要 #import <objc/runtime.h>
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
利用關(guān)聯(lián),自己書寫屬性的setter和getter方法,可以向category中添加屬性
NSString *const ZYBarButtonItem_badgeKey = @"ZYBarButtonItem_badgeKey";
@property (strong, nonatomic) UIView *badge;
- (UIView *)badge
{
UIView *badge = (UIView *)objc_getAssociatedObject(self, &ZYBarButtonItem_badgeKey);
if (!badge) {
badge = [[UIView alloc] init];
[self setBadge:badge];
[self initBadge];
[self.customView addSubview:badge];
}
return badge;
}
- (void)setBadge:(UIView *)badge
{
objc_setAssociatedObject(self, &ZYBarButtonItem_badgeKey, badge, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
初始化badge相關(guān)屬性:
- (void)initBadge
{
UIView *superview = nil;
if (self.customView) {
superview = self.customView;
superview.clipsToBounds = NO;
} else if ([self respondsToSelector:@selector(view)] && [(id)self view]) {
superview = [(id)self view];
}
[superview addSubview:self.badge];
// 默認(rèn)設(shè)置
self.badgeColor = [UIColor redColor];
self.badgeSize = 8;
self.badgeOriginX = 14;
self.badgeOriginY = 12;
self.badge.hidden = YES;
}
在提供給外部使用的屬性中噪奄,當(dāng)修改了默認(rèn)屬性時(shí) 需要刷新界面死姚,如修改badge顏色屬性badgeColor時(shí)人乓,在其setter方法中調(diào)用刷新方法:
- (void)setBadgeColor:(UIColor *)badgeColor
{
objc_setAssociatedObject(self, &LYBarButtonItem_badgeColorKey, badgeColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.badge) {
[self refreshBadge];
}
}
刷新方法:
- (void)refreshBadge
{
self.badge.frame = (CGRect){self.badgeOriginX,self.badgeOriginY,self.badgeSize,self.badgeSize};
self.badge.backgroundColor = self.badgeColor;
self.badge.layer.cornerRadius = self.badgeSize/2;
}
至此勤篮,項(xiàng)目需求的小紅點(diǎn)只需要通過控制badge的顯示或隱藏即可達(dá)到。若有其他需求類似顯示數(shù)字色罚,也可通過類似方法添加屬性來達(dá)成碰缔。