1.使用系統自帶的,並且可以在小紅點上顯示數字。
[itemOne setBadgeValue:@""]; //顯示不帶數字的小紅點 [itemOne setBadgeValue:@"1"];//顯示小紅點 並且帶數字
以上的缺點:小紅點太大了,傷不起啊!
2.使用圖片,創建圖片的時候,設置圖片的渲染。
UIImage * normalImage = [[UIImage imageNamed:@"pic_msg_yes_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; UIImage * selectImage = [[UIImage imageNamed:@"pic_msg_yes_sel"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; UITabBarItem *itemOne=[[UITabBarItem alloc]initWithTitle:@"消息" image:normalImage selectedImage:selectImage]; /**設置UIImage的渲染模式:UIImage.renderingMode 着色(Tint Color)是iOS7界面中的一個.設置UIImage的渲染模式:UIImage.renderingMode重大改變,你可以設置一個UIImage在渲染時是否使用當前視圖的Tint Color。UIImage新增了一個只讀屬性:renderingMode,對應的還有一個新增方法:imageWithRenderingMode:,它使用UIImageRenderingMode枚舉值來設置圖片的renderingMode屬性。該枚舉中包含下列值: UIImageRenderingModeAutomatic // 根據圖片的使用環境和所處的繪圖上下文自動調整渲染模式。 UIImageRenderingModeAlwaysOriginal // 始終繪制圖片原始狀態,不使用Tint Color。 UIImageRenderingModeAlwaysTemplate // 始終根據Tint Color繪制圖片,忽略圖片的顏色信息。 renderingMode屬性的默認值是UIImageRenderingModeAutomatic */
缺點:這樣就只能顯示小紅點了,無法顯示具體的數字。不過樓主的項目 不需要顯示數字,就用了這種。方便簡潔。
3.使用catgory,擴展UITabbar
此方法轉載自:http://blog.csdn.net/lilinoscar/article/details/47103747
第一步,建一個UITabBar的category類別。
第二步,編寫代碼。
.h文件
- #import <UIKit/UIKit.h>
- @interface UITabBar (badge)
- - (void)showBadgeOnItemIndex:(int)index; //顯示小紅點
- - (void)hideBadgeOnItemIndex:(int)index; //隱藏小紅點
- @end
.m文件
- #import "UITabBar+badge.h"
- #define TabbarItemNums 4.0 //tabbar的數量 如果是5個設置為5.0
- @implementation UITabBar (badge)
- //顯示小紅點
- - (void)showBadgeOnItemIndex:(int)index{
- //移除之前的小紅點
- [self removeBadgeOnItemIndex:index];
- //新建小紅點
- UIView *badgeView = [[UIView alloc]init];
- badgeView.tag = 888 + index;
- badgeView.layer.cornerRadius = 5;//圓形
- badgeView.backgroundColor = [UIColor redColor];//顏色:紅色
- CGRect tabFrame = self.frame;
- //確定小紅點的位置
- 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);//圓形大小為10
- [self addSubview:badgeView];
- }
- //隱藏小紅點
- - (void)hideBadgeOnItemIndex:(int)index{
- //移除小紅點
- [self removeBadgeOnItemIndex:index];
- }
- //移除小紅點
- - (void)removeBadgeOnItemIndex:(int)index{
- //按照tag值進行移除
- for (UIView *subView in self.subviews) {
- if (subView.tag == 888+index) {
- [subView removeFromSuperview];
- }
- }
- }
- @end
第三步,引入到需要使用的類中。
- #import "UITabBar+badge.h"
引用代碼如下:
- //顯示
- [self.tabBarController.tabBar showBadgeOnItemIndex:2];
- //隱藏
- [self.tabBarController.tabBar hideBadgeOnItemIndex:2]