您的位置:首页 > 产品设计 > UI/UE

某项目 需要在UITabbar 上显示小红点,在此搜罗了三个方法。

2015-08-31 10:52 537 查看
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文件

[objc] view plaincopy

#import <UIKit/UIKit.h>

@interface UITabBar (badge)

- (void)showBadgeOnItemIndex:(int)index; //显示小红点

- (void)hideBadgeOnItemIndex:(int)index; //隐藏小红点

@end

.m文件

[objc] view plaincopy

#import "UITabBar+badge.h"

#define TabbarItemNums 4.0 //tabbar的数量 如果是5个设置为5.0

@implementation UITabBar (badge)

[objc] view plaincopy

//显示小红点

- (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];

}

[objc] view plaincopy

//隐藏小红点

- (void)hideBadgeOnItemIndex:(int)index{

//移除小红点

[self removeBadgeOnItemIndex:index];

}

[objc] view plaincopy

//移除小红点

- (void)removeBadgeOnItemIndex:(int)index{

//按照tag值进行移除

for (UIView *subView in self.subviews) {

if (subView.tag == 888+index) {

[subView removeFromSuperview];

}

}

}

@end

第三步,引入到需要使用的类中。

[objc] view plaincopy

#import "UITabBar+badge.h"

引用代码如下:

[objc] view plaincopy

//显示

[self.tabBarController.tabBar showBadgeOnItemIndex:2];

//隐藏

[self.tabBarController.tabBar hideBadgeOnItemIndex:2]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: