失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > iOS 给控件View添加角标BadgeValue

iOS 给控件View添加角标BadgeValue

时间:2020-04-03 19:42:08

相关推荐

iOS 给控件View添加角标BadgeValue

代码

创建视图Badge继承自UIView

.h

#import <UIKit/UIKit.h>

@interface Badge : UIView

/**

* 给视图添加1、2、3、4角标

*/

- (void)addBadgeValue:(NSString *)badgeValue;

/**

* 移除添加的角标

*/

- (void)removeBadgeValue;

@end

.m

#import "Badge.h"

@implementation Badge

- (void)addBadgeValue:(NSString *)badgeValue {

[self removeBadgeValue];

UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];

UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"" image:nil tag:0];

item.badgeValue = badgeValue;

NSArray *array = [[NSArray alloc] initWithObjects:item, nil];

tabBar.items = array;

//寻找

for (UIView *viewTab in tabBar.subviews) {

for (UIView *subview in viewTab.subviews) {

NSString *strClassName = [NSString stringWithUTF8String:object_getClassName(subview)];

if ([strClassName isEqualToString:@"UITabBarButtonBadge"] ||

[strClassName isEqualToString:@"_UIBadgeView"]) {

//从原视图上移除

[subview removeFromSuperview];

//

[self addSubview:subview];

subview.frame = CGRectMake(self.frame.size.width-10, 0,

subview.frame.size.width, subview.frame.size.height);

return;

}

}

}

}

- (void)removeBadgeValue

{

for (UIView *subview in self.subviews) {

NSString *strClassName = [NSString stringWithUTF8String:object_getClassName(subview)];

if ([strClassName isEqualToString:@"UITabBarButtonBadge"] ||

[strClassName isEqualToString:@"_UIBadgeView"]) {

[subview removeFromSuperview];

break;

}

}

}

使用代码

#import "ViewController.h"

#import "Badge.h"

@interface ViewController ()

@property (nonatomic,strong)Badge *bd;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//角标

_bd = [[Badge alloc]init];

NSString *str = @"2";

[_bd addBadgeValue:str];

_bd.backgroundColor = [UIColor cyanColor];

_bd.frame = CGRectMake(100, 50, 100, 100);

[self.view addSubview:_bd];

}

@end

效果图如下

如果觉得《iOS 给控件View添加角标BadgeValue》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。