實(shí)現(xiàn)原理:
其實(shí)是自定義一個(gè)view瓦堵,將view添加到UITabBar上面,也可以是一個(gè)按鈕遏弱,設(shè)置背景圖片蜒灰,和label弦蹂。
廢話少說(shuō)直接上代碼
搞一個(gè)UITabBar的分類
#import <UIKit/UIKit.h>
@interface UITabBar (badge)
- (void)showBadgeOnItemIndex:(int)index;
- (void)hideBadgeOnItemIndex:(int)index;
@end
#import "UITabBar+badge.h"
#define TabbarItemNums 5.0
@implementation UITabBar (badge)
//顯示紅點(diǎn)
- (void)showBadgeOnItemIndex:(int)index{
[self removeBadgeOnItemIndex:index];
//新建小紅點(diǎn)
UIView *bview = [[UIView alloc]init];
bview.tag = 888+index;
bview.layer.cornerRadius = 5;
bview.clipsToBounds = YES;
bview.backgroundColor = [UIColor redColor];
CGRect tabFram = self.frame;
float percentX = (index+0.6)/TabbarItemNums;
CGFloat x = ceilf(percentX*tabFram.size.width);
CGFloat y = ceilf(0.1*tabFram.size.height);
bview.frame = CGRectMake(x, y, 10, 10);
[self addSubview:bview];
[self bringSubviewToFront:bview];
}
//隱藏紅點(diǎn)
-(void)hideBadgeOnItemIndex:(int)index{
[self removeBadgeOnItemIndex:index];
}
//移除控件
- (void)removeBadgeOnItemIndex:(int)index{
for (UIView*subView in self.subviews) {
if (subView.tag == 888+index) {
[subView removeFromSuperview];
}
}
}
@end
最后在子控制器調(diào)用就可以啦
#import "UITabBar+badge.h"
[self.tabBarController.tabBar showBadgeOnItemIndex:4];
swift代碼
import UIKit
extension UITabBar {
func showBadgeOnItem(index:Int, count:Int) {
removeBadgeOnItem(index: index)
let bview = UIView.init()
bview.tag = 888+index
bview.layer.cornerRadius = 9
bview.clipsToBounds = true
bview.backgroundColor = UIColor.red
let tabFrame = self.frame
let percentX = (Float(index)+0.6)/5.0(tabBar的總個(gè)數(shù))
let x = CGFloat(ceilf(percentX*Float(tabFrame.width)))
let y = CGFloat(ceilf(0.1*Float(tabFrame.height)))
bview.frame = CGRect(x: x, y: y, width: 18, height: 18)
let cLabel = UILabel.init()
cLabel.text = "\(count)"
cLabel.frame = CGRect(x: 0, y: 0, width: 18, height: 18)
cLabel.font = UIFont.systemFont(ofSize: 10)
cLabel.textColor = UIColor.white
cLabel.textAlignment = .center
bview.addSubview(cLabel)
addSubview(bview)
bringSubview(toFront: bview)
}
//隱藏紅點(diǎn)
func hideBadgeOnItem(index:Int) {
removeBadgeOnItem(index: index)
}
//移除控件
func removeBadgeOnItem(index:Int) {
for subView:UIView in subviews {
if subView.tag == 888+index {
subView.removeFromSuperview()
}
}
}
}
注意:如果是iPad等其他原因造成的位置問(wèn)題,可以自己更改里面的坐標(biāo)算法.調(diào)整到自己合適的位置.具體就不贅述啦