iOS之基本控制元件和tabBar右上角角標顯示與隱藏
阿新 • • 發佈:2019-02-20
#import #import "UIView+redPoint.h" #define USERDEF [NSUserDefaults standardUserDefaults] @implementation UIView (redPoint) #pragma other(redPoint) //新增顯示 - (void)showRedAtOffSetX:(float)offsetX AndOffSetY:(float)offsetY OrValue:(NSString *)value{ [self removeRedPoint];//新增之前先移除,避免重複新增 //新建小紅點 UIView *badgeView = [[UIView alloc]init]; badgeView.tag = 998; CGFloat viewWidth = 12; if (value) { viewWidth = 18; UILabel *valueLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, viewWidth, viewWidth)]; valueLbl.text = value; valueLbl.font = [UIFont systemFontOfSize:12]; valueLbl.textColor = [UIColor whiteColor]; valueLbl.textAlignment = NSTextAlignmentCenter; valueLbl.clipsToBounds = YES; [badgeView addSubview:valueLbl]; } badgeView.layer.cornerRadius = viewWidth / 2; badgeView.backgroundColor = [UIColor redColor]; CGRect tabFrame = self.frame; //確定小紅點的位置 if (offsetX == 0) { // offsetX = 1; offsetX = -viewWidth/2.0; } if (offsetY == 0) { // offsetY = 0.05; offsetY = -viewWidth/2.0; } CGFloat x = ceilf(tabFrame.size.width + offsetX); CGFloat y = 0; if (offsetY == -viewWidth/2.0) { y = ceilf(offsetY); }else{ y = ceilf(offsetY * tabFrame.size.height); } badgeView.frame = CGRectMake(x, y, viewWidth, viewWidth); [self addSubview:badgeView]; } //隱藏 - (void)hideRedPoint{ [self removeRedPoint]; } //移除 - (void)removeRedPoint{ //按照tag值進行移除 for (UIView *subView in self.subviews) { if (subView.tag == 998) { [subView removeFromSuperview]; } } } #pragma mark Tabbar(redPoint) //顯示小紅點 - (void)showBadgeOnItemIndex:(int)index{ NSString *keyStr = [NSString stringWithFormat:@"%d_HADSET",index]; if ([USERDEF objectForKey:keyStr]) { return; } else { [USERDEF setObject:@"HADSET" forKey:keyStr]; } //移除之前可能存在的小紅點 [self removeBadgeOnItemIndex:index]; //新建小紅點 UIView *badgeView = [[UIView alloc]init]; badgeView.tag = 888 + index; badgeView.layer.cornerRadius = 6; badgeView.backgroundColor = [UIColor redColor]; CGRect tabFrame = self.frame; //確定小紅點的位置 float percentX = (index +0.55) / 5; //5為tabbaritem的總個數 CGFloat x = ceilf(percentX * tabFrame.size.width); CGFloat y = ceilf(0.05 * tabFrame.size.height); badgeView.frame = CGRectMake(x, y, 12, 12); [self addSubview:badgeView]; } //隱藏小紅點 - (void)hideBadgeOnItemIndex:(int)index{ NSString *keyStr = [NSString stringWithFormat:@"%d_HADSET",index]; //移除小紅點 [self removeBadgeOnItemIndex:index]; if ([USERDEF objectForKey:keyStr]) { [USERDEF removeObjectForKey:keyStr]; } } //移除 - (void)removeBadgeOnItemIndex:(int)index{ //按照tag值進行移除 for (UIView *subView in self.subviews) { if (subView.tag == 888+index) { [subView removeFromSuperview]; } } } @end