UITabBar+badge.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // UITabBar+badge.m
  3. // WFChat UIKit
  4. //
  5. // Created by WF Chat on 2017/9/12.
  6. // Copyright © 2017年 WildFireChat. All rights reserved.
  7. //
  8. #import "UITabBar+badge.h"
  9. #import "TabbarButton.h"
  10. #import "WFCUImage.h"
  11. @implementation UITabBar (badge)
  12. - (void)showBadgeOnItemIndex:(int)index{
  13. [self showBadgeOnItemIndex:index badgeValue:0];
  14. }
  15. - (void)showBadgeOnItemIndex:(int)index badgeValue:(int)badgeValue{
  16. //移除之前的小红点
  17. [self removeBadgeOnItemIndex:index];
  18. if (badgeValue > 0) {
  19. //新建小红点
  20. CGRect tabFrame = self.frame;
  21. //确定小红点的位置
  22. float percentX = (index + 0.5) / self.items.count;
  23. CGFloat x = ceilf(percentX * tabFrame.size.width) + 8;
  24. CGFloat y = ceilf(0.07 * tabFrame.size.height) - 5;
  25. if (badgeValue <= 0) {
  26. [self initUnreadCountButton:CGRectMake(x, y, 10, 10) tag:888+index badgeValue:0];
  27. }
  28. if (badgeValue < 10 && badgeValue > 0) {
  29. [self initUnreadCountButton:CGRectMake(x, y, 18, 18) tag:888+index badgeValue:badgeValue];
  30. }
  31. if (badgeValue >= 10 && badgeValue < 100 ) {
  32. [self initUnreadCountButton:CGRectMake(x, y, 22, 18) tag:888+index badgeValue:badgeValue];
  33. }
  34. if (badgeValue >= 100) {
  35. TabbarButton *btn = [[TabbarButton alloc] initWithFrame:CGRectMake(x, y, 22, 18)];
  36. UIImage *image = [[WFCUImage imageNamed:@"more_unread"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  37. [btn setImage:image forState:UIControlStateNormal];
  38. [self addSubview:btn];
  39. btn.tag = 888+index;
  40. // btn.layer.cornerRadius = 9;//圆形
  41. }
  42. }
  43. }
  44. //隐藏小红点
  45. - (void)hideBadgeOnItemIndex:(int)index{
  46. //移除小红点
  47. [self removeBadgeOnItemIndex:index];
  48. }
  49. //移除小红点
  50. - (void)removeBadgeOnItemIndex:(int)index{
  51. //按照tag值进行移除
  52. for (UIView *subView in self.subviews) {
  53. if (subView.tag == 888+index) {
  54. [((TabbarButton *)subView).shapeLayer removeFromSuperlayer];
  55. [subView removeFromSuperview];
  56. }
  57. }
  58. }
  59. -(void)initUnreadCountButton:(CGRect)frame tag:(NSUInteger)tag badgeValue:(int)badgeValue
  60. {
  61. TabbarButton *btn = [[TabbarButton alloc] initWithFrame:frame];
  62. [self addSubview:btn];
  63. btn.tag = tag;
  64. btn.layer.cornerRadius = frame.size.height / 2.f;//圆形
  65. NSString *value = @"";
  66. if (badgeValue > 0) {
  67. value = [NSString stringWithFormat:@"%d",badgeValue];
  68. } else {
  69. btn.userInteractionEnabled = NO;
  70. }
  71. btn.unreadCount = value;
  72. }
  73. @end