在我們的項(xiàng)目經(jīng)常會(huì)遇到這樣的需求:當(dāng)有新消息出現(xiàn)的時(shí)候搪缨,需要顯示一個(gè)小紅點(diǎn)提醒用戶有新消息了。效果如圖:
下面是代碼:
為UITabBar寫(xiě)一個(gè)Category
.h中:
#import <UIKit/UIKit.h>
@interface UITabBar (badge)
//顯示小紅點(diǎn)
- (void)showBadgeOnItemIndex:(int)index;
//隱藏小紅點(diǎn)
- (void)hideBadgeOnItemIndex:(int)index;
@end
#import "UITabBar+badge.h"
#define TabbarItemNums 5.0 //tabbar的數(shù)量
@implementation UITabBar (badge)
- (void)showBadgeOnItemIndex:(int)index{
//移除之前的小紅點(diǎn)
[self removeBadgeOnItemIndex:index];
//新建小紅點(diǎn)
UIView *badgeView = [[UIView alloc]init];
badgeView.tag = 888 + index;
badgeView.layer.cornerRadius = 5;
badgeView.backgroundColor = [UIColor redColor];
CGRect tabFrame = self.frame;
//確定小紅點(diǎn)的位置
float percentX = (index +0.6) / TabbarItemNums;
CGFloat x = ceilf(percentX * tabFrame.size.width);
CGFloat y = ceilf(0.1 * tabFrame.size.height);
badgeView.frame = CGRectMake(x, y, 10, 10);
[self addSubview:badgeView];
}
- (void)hideBadgeOnItemIndex:(int)index{
//移除小紅點(diǎn)
[self removeBadgeOnItemIndex:index];
}
- (void)removeBadgeOnItemIndex:(int)index{
//按照tag值進(jìn)行移除
for (UIView *subView in self.subviews) {
if (subView.tag == 888+index) {
[subView removeFromSuperview];
}
}
}
@end
在需要的地方調(diào)用:
如:
[tabBar showBadgeOnItemIndex:3];