iOS开发-自定义TabbarController与Tabbar按钮Badge角标

iOS开发-自定义Tabbar按钮Badge角标

Tabbar是放在APP底部的控件。UITabbarController是一个非常常见的一种展示模式了。比如微信、QQ都是使用tabbar来进行功能分类的管理。
iOS开发-自定义TabbarController与Tabbar按钮Badge角标_第1张图片

一、实现自定义Tabbar

我这里Tabbar继承于系统的UITabBar,定义背景图、线条的颜色、tabbarItem列表等属性

@property (nonatomic, strong) UIImage *bgroundImage;                //背景图
@property (nonatomic, strong) UIColor *lineColor;                   //线条的颜色
@property (nonatomic, strong) NSArray *dataSources;                 //tabbarItem列表
@property (nonatomic, assign) BOOL showLine;                        //线条的颜色
@property (nonatomic, assign) NSInteger selectedIndex;

SDTabBarDelegate协议,当点击了Tabbar某一个按钮,告知点击了index

@protocol SDTabBarDelegate <NSObject>

- (void)tabBar:(SDTabBar *)tabBar tabDidSelectedIndex:(NSInteger)index;

@end

代码如下

SDTabBar.h

#import <UIKit/UIKit.h>
#import "SDTabbarButton.h"

@protocol SDTabBarDelegate;
@interface SDTabBar : UITabBar

@property (nonatomic, weak) id<SDTabBarDelegate>tabDelegate;        //代理
@property (nonatomic, strong) UIImage *bgroundImage;                //背景图
@property (nonatomic, strong) UIColor *lineColor;                   //线条的颜色
@property (nonatomic, strong) NSArray *dataSources;                 //tabbarItem列表
@property (nonatomic, assign) BOOL showLine;                        //线条的颜色

@property (nonatomic, assign) NSInteger selectedIndex;              //选中的tabbar按钮index

- (instancetype)initWithFrame:(CGRect)frame;

/**
 更新tabbar样式

 @param tabbarItem item
 */
- (void)updateTabbarStyle:(SDTabbarItem *)tabbarItem;

@end

@protocol SDTabBarDelegate <NSObject>

- (void)tabBar:(SDTabBar *)tabBar tabDidSelectedIndex:(NSInteger)index;

@end

SDTabBar.m

#import "SDTabBar.h"
#import "SDBaseView.h"

static CGFloat kLineHeight = 1.0;
static CGFloat kPadding = 5.0;

@interface SDTabBar ()

@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UIImageView *lineImageView;
@property (nonatomic, assign) CGFloat safeInsetBottom;

@end

@implementation SDTabBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.bgImageView];
        [self addSubview:self.lineImageView];
        
        [self hidenTopLine];
        self.showLine = NO;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.bgImageView.frame = self.bounds;
    self.safeInsetBottom = [SDBaseView baseSafeEdgeInsets].bottom;

    if (self.dataSources && self.dataSources.count > 0) {
        CGFloat width = CGRectGetWidth(self.bounds) / self.dataSources.count;
        CGFloat height = CGRectGetHeight(self.bounds);
        for (UIView *subView in self.subviews) {
            if ([subView isKindOfClass:[SDTabbarButton class]]) {
                SDTabbarButton *tabbarButton = (SDTabbarButton *)subView;
                CGRect imageBounds = CGRectMake(0.0, 0.0, width, height);
                CGPoint imageCenter = CGPointMake((tabbarButton.tag + 0.5) * width, height/2 - self.safeInsetBottom/2);
                tabbarButton.bounds = imageBounds;
                tabbarButton.center = imageCenter;
            }
        }
    }
    
    self.lineImageView.frame = CGRectMake(0.0, 0.0, CGRectGetWidth(self.bgImageView.frame), kLineHeight);
    
    [self setTabbarSubview];
}

/**
 更新系统tabbar的选中状态
 */
- (void)updateTabbarButtons {
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[SDTabbarButton class]]) {
            SDTabbarButton *tabbarButton = (SDTabbarButton *)subView;
            if (tabbarButton.tag == self.selectedIndex) {
                tabbarButton.selected = YES;
            } else {
                tabbarButton.selected = NO;
            }
        }
    }
}

/**
 隐藏系统的tabbarButton
 */
- (void)setTabbarSubview {
    for (UIView *child in self.subviews) {
        Class class = NSClassFromString(@"UITabBarButton");
        if ([child isKindOfClass:class]) {
            child.hidden = YES;
        }
    }
}

/**
 重新创建tabbarButtons
 */
- (void)setupTabbarButtons {
    
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[SDTabbarButton class]]) {
            [subView removeFromSuperview];
        }
    }
    
    for (NSInteger index = 0; index < self.dataSources.count; index ++) {
        SDTabbarItem *tabbarItem = [self.dataSources objectAtIndex:index];
        SDTabbarButton *tabbarButton = [[SDTabbarButton alloc] initWithFrame:CGRectZero];
        tabbarButton.userInteractionEnabled = YES;
        tabbarButton.tabbarItem = tabbarItem;
        tabbarButton.tag = index;
        [tabbarButton addTarget:self action:@selector(tabbarButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:tabbarButton];
    }
    
    [self.bgImageView bringSubviewToFront:self.lineImageView];
    
    [self setNeedsLayout];
}

- (void)setDataSources:(NSArray *)dataSources {
    _dataSources = dataSources;
    [self setupTabbarButtons];
    [self setNeedsLayout];
}

- (void)setBgroundImage:(UIImage *)bgroundImage {
    _bgroundImage = bgroundImage;
    self.bgImageView.image = bgroundImage;
    [self setNeedsLayout];
}

- (void)setLineColor:(UIColor *)lineColor {
    _lineColor = lineColor;
    self.lineImageView.backgroundColor = lineColor;
    [self setNeedsLayout];
}

- (void)setShowLine:(BOOL)showLine {
    _showLine = showLine;
    self.lineImageView.hidden = !showLine;
    [self setNeedsLayout];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    [self updateTabbarButtons];
    if (self.tabDelegate && [self.tabDelegate respondsToSelector:@selector(tabBar:tabDidSelectedIndex:)]) {
        [self.tabDelegate tabBar:self tabDidSelectedIndex:selectedIndex];
    }
}

/**
 更新tabbar样式
 
 @param tabbarItem item
 */
- (void)updateTabbarStyle:(SDTabbarItem *)tabbarItem {
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[SDTabbarButton class]]) {
            SDTabbarButton *tabbarButton = (SDTabbarButton *)subView;
            SDTabbarItem *item = tabbarButton.tabbarItem;
            if (tabbarItem.identifier && [tabbarItem.identifier isEqualToString:item.identifier]) {
                //更新tabbar
                [item copyClone:tabbarItem];
                tabbarButton.tabbarItem = item;
                break;
            }
        }
    }
}

#pragma mark - Actions
- (void)tabbarButtonSelected:(SDTabbarButton *)tabbarButton {
    self.selectedIndex = tabbarButton.tag;
}

- (void)hidenTopLine {
    CGRect rect = [UIScreen mainScreen].bounds;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self setBackgroundImage:img];
    [self setShadowImage:img];
}

#pragma mark - GETTER
- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _bgImageView.backgroundColor = [UIColor clearColor];
        _bgImageView.clipsToBounds = YES;
    }
    return _bgImageView;
}

- (UIImageView *)lineImageView {
    if (!_lineImageView) {
        _lineImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _lineImageView.backgroundColor = [UIColor colorWithHexString:@"f3f3f3" alpha:1.0];
    }
    return _lineImageView;
}

@end

二、定义tabbar按钮

定义tabbar的按钮,定义显示的icon、标题、badge背景、badge显示等。

@property (nonatomic, strong) DFTabbarItem *tabbarItem;
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UIImageView *badgeImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *badgeLabel;

tabbar按钮SDTabbarButton

SDTabbarButton.h

#import <UIKit/UIKit.h>
#import "SDTabbarItem.h"

@interface SDTabbarButton : UIControl

@property (nonatomic, strong) SDTabbarItem *tabbarItem;

- (instancetype)initWithFrame:(CGRect)frame;

@end

SDTabbarButton.m

#import "SDTabbarButton.h"

static CGFloat kIconSize = 26.0;
static CGFloat kTitleHeight = 18.0;
static CGFloat kBadgeSize = 8.0;
static CGFloat kPadding = 5.0;
static CGFloat defaultBadgeRadius = 9.0;
static CGFloat defaultDotRadius = 5.0;

#define kTabbarDotShown @"dotShown"
#define kTabbarBadge @"badge"

@interface SDTabbarButton ()

@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UIImageView *badgeImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *badgeLabel;

@end

@implementation SDTabbarButton

#pragma mark - INIT
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.iconImageView];
        [self addSubview:self.titleLabel];
        [self addSubview:self.badgeImageView];
        [self addSubview:self.badgeLabel];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGSize titleSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font forMaxSize:CGSizeMake(CGRectGetWidth(self.bounds), kTitleHeight)];
    
    CGFloat titleHeight = MIN(ceil(titleSize.height), kTitleHeight);
    
    self.iconImageView.frame = CGRectMake((CGRectGetWidth(self.bounds) - kIconSize)/2, (CGRectGetHeight(self.bounds) - kIconSize - titleHeight)/2, kIconSize, kIconSize);
    
    self.titleLabel.frame = CGRectMake(0.0, CGRectGetMaxY(self.iconImageView.frame), CGRectGetWidth(self.bounds), titleHeight);
    self.badgeImageView.frame = CGRectMake(CGRectGetMaxX(self.iconImageView.frame), CGRectGetMinY(self.iconImageView.frame) + kPadding, kBadgeSize, kBadgeSize);
    
    CGSize badgeSize = [self.badgeLabel.text sizeWithFont:self.badgeLabel.font forMaxSize:CGSizeMake(20.0, 20.0)];
    CGFloat minWidth = MAX(defaultBadgeRadius * 2, badgeSize.width + 10.0);
    CGFloat minHight = MAX(defaultBadgeRadius * 2, badgeSize.height);
    
    CGRect badgeBounds = CGRectMake(0.0, 0.0, minWidth, minHight);
    CGPoint badgeCenter = CGPointMake(CGRectGetMidX(self.iconImageView.frame) + CGRectGetHeight(badgeBounds), CGRectGetMidY(self.iconImageView.frame) - CGRectGetHeight(badgeBounds)/2 + 5.0);
    self.badgeLabel.bounds = badgeBounds;
    self.badgeLabel.center = badgeCenter;
    self.badgeLabel.layer.cornerRadius = minHight / 2;
}

#pragma mark - SETTER
- (void)setTabbarItem:(SDTabbarItem *)tabbarItem {
    _tabbarItem = tabbarItem;
    
    //设置icon
    self.iconImageView.image = tabbarItem.image;
    
    //设置标题
    self.titleLabel.font = tabbarItem.titleFont;
    self.titleLabel.textColor = tabbarItem.titleColor;
    self.titleLabel.text = [NSString stringWithFormat:@"%@",(tabbarItem.title?tabbarItem.title:@"")];

    //设置红点
    self.badgeImageView.hidden = !tabbarItem.dotShown;
    
    //设置badge
    self.badgeLabel.backgroundColor = tabbarItem.badgeColor;
    self.badgeLabel.text = [NSString stringWithFormat:@"%@",(tabbarItem.badge?tabbarItem.badge:@"")];
    if(tabbarItem.badge && tabbarItem.badge.length > 0) {
        self.badgeLabel.hidden = NO;
    } else {
        self.badgeLabel.hidden = YES;
    }
    
    [self addObserver];
    [self setNeedsLayout];
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    if (selected) {
        self.titleLabel.textColor = self.tabbarItem.selectedTitleColor;
        self.iconImageView.image = self.tabbarItem.selectedImage;
    } else {
        self.titleLabel.textColor = self.tabbarItem.titleColor;
        self.iconImageView.image = self.tabbarItem.image;
    }
}

#pragma mark - GETTER
- (UIImageView *)iconImageView {
    if (!_iconImageView) {
        _iconImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _iconImageView.backgroundColor = [UIColor clearColor];
        _iconImageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _iconImageView;
}

- (UIImageView *)badgeImageView {
    if (!_badgeImageView) {
        _badgeImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _badgeImageView.backgroundColor = [UIColor clearColor];
        _badgeImageView.frame = CGRectMake(0.0, 0.0, kBadgeSize, kBadgeSize);
        _badgeImageView.layer.cornerRadius = kBadgeSize/2;
        _badgeImageView.layer.masksToBounds = YES;
        _badgeImageView.hidden = YES;
    }
    return _badgeImageView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UILabel *)badgeLabel {
    if (!_badgeLabel) {
        _badgeLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _badgeLabel.backgroundColor = [UIColor clearColor];
        _badgeLabel.textAlignment = NSTextAlignmentCenter;
        _badgeLabel.clipsToBounds = YES;
        _badgeLabel.textColor = [UIColor whiteColor];
        _badgeLabel.font = [UIFont systemFontOfSize:12.0];
    }
    return _badgeLabel;
}

#pragma mark KVO Refresh
- (void)addObserver{
    @try {
        NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
        [self.tabbarItem addObserver:self forKeyPath:kTabbarDotShown options:options context:nil];
        [self.tabbarItem addObserver:self forKeyPath:kTabbarBadge options:options context:nil];
    } @catch (NSException *exception) {
        NSLog(@"exception:%@",exception);
    }
}

- (void)removeObserver{
    @try {
        [self.tabbarItem removeObserver:self forKeyPath:kTabbarDotShown context:nil];
        [self.tabbarItem removeObserver:self forKeyPath:kTabbarBadge context:nil];
    } @catch (NSException *exception) {
        NSLog(@"exception:%@",exception);
    }
}

//监听页面contentOffset
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([kTabbarBadge isEqualToString:keyPath]) {
        NSString *badge = self.tabbarItem.badge;
        self.badgeLabel.text = [NSString stringWithFormat:@"%@",(badge?badge:@"")];
        if(badge && badge.length > 0) {
            self.badgeLabel.hidden = NO;
        } else {
            self.badgeLabel.hidden = YES;
        }
        return;
    }
    
    if ([kTabbarDotShown isEqualToString:keyPath]) {
        //设置红点
        self.badgeImageView.hidden = !self.tabbarItem.dotShown;
        return;
    }
}

- (void)dealloc {
    [self removeObserver];
}

@end

定义tabbarItem,确定icon、title、badge等

SDTabbarItem.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface SDTabbarItem : NSObject

@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) UIFont *titleFont;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImage *selectedImage;
@property (nonatomic, strong) UIColor *titleColor;
@property (nonatomic, strong) UIColor *selectedTitleColor;
@property (nonatomic, strong) UIColor *badgeColor;
@property (nonatomic, strong) NSString *badge;
@property (nonatomic, assign) BOOL dotShown;

/**
 赋值

 @param item item
 */
- (void)copyClone:(SDTabbarItem *)item;

- (id)initWithTitle:(NSString *)title
          titleFont:(UIFont *)titleFont
              image:(UIImage *)image
      selectedImage:(UIImage *)selectedImage
         titleColor:(UIColor *)titleColor
 selectedTitleColor:(UIColor *)selectedTitleColor
         badgeColor:(UIColor *)badgeColor;

@end

SDTabbarItem.m

#import "SDTabbarItem.h"

@implementation SDTabbarItem

- (id)initWithTitle:(NSString *)title
          titleFont:(UIFont *)titleFont
              image:(UIImage *)image
      selectedImage:(UIImage *)selectedImage
         titleColor:(UIColor *)titleColor
 selectedTitleColor:(UIColor *)selectedTitleColor
         badgeColor:(UIColor *)badgeColor {
    self = [super init];
    if (self) {
        self.title = title;
        self.titleFont = titleFont;
        self.image = image;
        self.selectedImage = selectedImage;
        self.titleColor = titleColor;
        self.selectedTitleColor = selectedTitleColor;
        self.badge = [[NSString alloc] init];
        self.dotShown = NO;
        self.badgeColor = badgeColor;
    }
    return self;
}

/**
 赋值
 
 @param item item
 */
- (void)copyClone:(SDTabbarItem *)item {
    self.title = item.title;
    self.image = item.image;
    self.selectedImage = item.selectedImage;
    self.titleColor = item.titleColor;
    self.selectedTitleColor = item.selectedTitleColor;
    self.badgeColor = item.badgeColor;
}

@end

三、实现自定义TabbarController

在SDTabBarController的viewDidLoad执行[self setValue:_sdTabbar forKey:@“tabBar”];
注意:该方法替换TabbarController默认的tabbar

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _sdTabbar = [[SDTabBar alloc] initWithFrame:CGRectZero];
    _sdTabbar.frame = self.tabBar.bounds;
    _sdTabbar.tabDelegate  = self;
    
    //UIImage *bgImage = [UIImage imageNamed:@"bg_tabbar"];
    UIImage *bgImage = [UIImage imageWithColor:[UIColor colorWithHexString:@"ffffff"] size:CGSizeMake(20, 20)];
    bgImage = [bgImage stretchableImageWithLeftCapWidth:bgImage.leftCapWidth*0.5 topCapHeight:bgImage.topCapHeight*0.5];
    _sdTabbar.bgroundImage = bgImage;

    _sdTabbar.backgroundImage = bgImage;

    [self setValue:_sdTabbar forKey:@"tabBar"];
}

SDTabBarController来控制tabbar元素点击对应的controller。

@property (nonatomic, strong) NSArray *tabViewControllers;

当点击按钮某一条时候,更改TabbarController的selectedIndex

- (void)tabBar:(SDTabBar *)tabBar tabDidSelectedIndex:(NSInteger)index {
    self.selectedIndex = index;
}

代码如下

SDTabBarController.h

#import <UIKit/UIKit.h>
#import "SDTabBar.h"

@interface SDTabBarController : UITabBarController<UINavigationControllerDelegate>

@property (nonatomic, strong, readonly) UINavigationController *selectedNavigationController;
@property (nonatomic, strong) NSArray *tabViewControllers;
@property (nonatomic, strong) SDTabBar *sdTabbar;

- (void)reset;

@end

SDTabBarController.m

#import "SDTabBarController.h"
#import "UIViewController+TabBarItem.h"

#define K_TAB_DEFAULT_INDEX  0

@interface SDTabBarController ()<SDTabBarDelegate>

@property (nonatomic, strong, readwrite) UINavigationController *selectedNavigation;

@end

@implementation SDTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _sdTabbar = [[SDTabBar alloc] initWithFrame:CGRectZero];
    _sdTabbar.frame = self.tabBar.bounds;
    _sdTabbar.tabDelegate  = self;
    
    //UIImage *bgImage = [UIImage imageNamed:@"bg_tabbar"];
    UIImage *bgImage = [UIImage imageWithColor:[UIColor colorWithHexString:@"ffffff"] size:CGSizeMake(20, 20)];
    bgImage = [bgImage stretchableImageWithLeftCapWidth:bgImage.leftCapWidth*0.5 topCapHeight:bgImage.topCapHeight*0.5];
    _sdTabbar.bgroundImage = bgImage;

    _sdTabbar.backgroundImage = bgImage;

    [self setValue:_sdTabbar forKey:@"tabBar"];
}

#pragma mark - SETTER
- (void)setTabViewControllers:(NSArray *)tabViewControllers {
    _tabViewControllers = tabViewControllers;
    
    NSMutableArray *tabbarItems = [NSMutableArray arrayWithCapacity:0];
    for (UIViewController *viewController in tabViewControllers) {
        SDTabbarItem *item = nil;
        if ([viewController isKindOfClass:[UINavigationController class]]) {
            item = ((UIViewController *)((UINavigationController *)viewController).viewControllers.firstObject).sdTabbarItem;
        } else {
            item = viewController.sdTabbarItem;
        }
        [tabbarItems addObject:item];
    }
    
    self.sdTabbar.dataSources = tabbarItems;
    
    self.viewControllers = tabViewControllers;
    self.sdTabbar.selectedIndex = K_TAB_DEFAULT_INDEX;
}

#pragma mark - SDTabBarDelegate
- (void)tabBar:(SDTabBar *)tabBar tabDidSelectedIndex:(NSInteger)index {
    self.selectedIndex = index;
}

#pragma mark - reset
- (void)reset {
    if ([self.selectedViewController isKindOfClass:[UINavigationController class]]) {
        [self.selectedViewController popToRootViewControllerAnimated:NO];
    } else {
        [self.selectedViewController.navigationController popToRootViewControllerAnimated:NO];
    }
    
    [self.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[UINavigationController class]]) {
            [(UINavigationController *)obj popToRootViewControllerAnimated:NO];
        }
    }];
    
    [self.sdTabbar setSelectedIndex:K_TAB_DEFAULT_INDEX];
}

- (NSUInteger)selectedIndex {
    return self.sdTabbar.selectedIndex;
}

- (UINavigationController *)selectedNavigationController {
    return (UINavigationController *)[self.tabViewControllers objectAtIndex:self.sdTabbar.selectedIndex];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

四、为UIViewController扩展属性TabBarItem

我这里为UIViewController扩展属性TabBarItem,方法TabbarController的viewControllers中的ViewController方法更改TabBarItem样式。

UIViewController+TabBarItem.h

#import <UIKit/UIKit.h>
#import "SDTabbarItem.h"

@interface UIViewController (TabBarItem)

@property (nonatomic, strong) SDTabbarItem *sdTabbarItem;

@end

UIViewController+TabBarItem.m

#import "UIViewController+TabBarItem.h"
#import <objc/runtime.h>

static const void *tabBarItemKey = &tabBarItemKey;

@implementation UIViewController (TabBarItem)

- (SDTabbarItem *)sdTabbarItem {
    return objc_getAssociatedObject(self, tabBarItemKey);
}

- (void)setSdTabbarItem:(SDTabbarItem *)sdTabbarItem {
    objc_setAssociatedObject(self, tabBarItemKey, sdTabbarItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

五、使用自定义的Tabbar

使用SDMainTabBarController来继承SDTabBarController,配置viewControllers与按钮显示的TabbarItems

SDMainTabBarController.h

#import "SDTabBarController.h"

@interface SDMainTabBarController : SDTabBarController

- (void)clearBadgeNumber;

- (void)showTabBar:(BOOL)show;

@end

SDMainTabBarController.m

#import "SDMainTabBarController.h"
#import "UIViewController+TabBarItem.h"
#import "INMineViewController.h"
#import "INDiscoveryViewController.h"
#import "INAddressBookViewController.h"
#import "INConversationViewController.h"
#import "SDBaseNavigationController.h"
#import "UIColor+Addition.h"
#import "UIImage+Color.h"

#import "SDAppThemeDownloadManager.h"
#import "SDAppThemeManager.h"

@interface SDMainTabBarController ()

@property (nonatomic, strong) INMineViewController *mineVC;
@property (nonatomic, strong) INConversationViewController *conversationVC;
@property (nonatomic, strong) INAddressBookViewController *addressBookVC;
@property (nonatomic, strong) INDiscoveryViewController *discoveryVC;

@end

@implementation SDMainTabBarController

- (id)init {
    self  = [super init];
    if (self) {
        [self initControllers];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(systemAppThemeChanged:) name:K_APP_THEME_CHANGED object:nil];
    }
    return self;
}

- (void)initControllers {
    
    //我的
    self.mineVC = [[INMineViewController alloc] init];
    
    SDBaseNavigationController *mineNav = [[SDBaseNavigationController alloc] initWithRootViewController:self.mineVC];
    mineNav.delegate = self;
    
    //消息
    self.conversationVC = [[INConversationViewController alloc] init];
    SDBaseNavigationController *conversationNav = [[SDBaseNavigationController alloc] initWithRootViewController:self.conversationVC];
    conversationNav.delegate = self;
    
    //通讯录
    self.addressBookVC = [[INAddressBookViewController alloc] init];
    SDBaseNavigationController *addressBookNav = [[SDBaseNavigationController alloc] initWithRootViewController:self.addressBookVC];
    addressBookNav.delegate = self;
    
    //挖矿
    self.discoveryVC = [[INDiscoveryViewController alloc] init];
    SDBaseNavigationController *coinNav = [[SDBaseNavigationController alloc] initWithRootViewController:self.discoveryVC];
    coinNav.delegate = self;
    
    UIColor *titleColor = [UIColor colorWithHexString:@"B0B0B0"];
    
    UIColor *selectedColor = [UIColor colorWithHexString:@"171013"];
    
    UIColor *badgeColor = [UIColor colorWithHexString:@"FC3F51"];
    
    UIFont *titleFont = [UIFont systemFontOfSize:10];
    
    SDTabbarItem *item1 = [[SDTabbarItem alloc] initWithTitle:@"消息" titleFont:titleFont image:[UIImage imageNamed:@"ic_tab_home"] selectedImage:[UIImage imageNamed:@"ic_tab_home_selected"] titleColor:titleColor selectedTitleColor:selectedColor badgeColor:badgeColor];
    item1.identifier = @"home";
    self.conversationVC.sdTabbarItem = item1;
    
    SDTabbarItem *item2 = [[SDTabbarItem alloc] initWithTitle:@"通讯录" titleFont:titleFont image:[UIImage imageNamed:@"ic_tab_message"] selectedImage:[UIImage imageNamed:@"ic_tab_message_selected"] titleColor:titleColor selectedTitleColor:selectedColor badgeColor:badgeColor];
    item2.identifier = @"addressbook";
    self.addressBookVC.sdTabbarItem = item2;

    SDTabbarItem *item3 = [[SDTabbarItem alloc] initWithTitle:@"发现" titleFont:titleFont image:[UIImage imageNamed:@"ic_tab_discover"] selectedImage:[UIImage imageNamed:@"ic_tab_discover_selected"] titleColor:titleColor selectedTitleColor:selectedColor badgeColor:badgeColor];
    item3.identifier = @"discovery";
    self.discoveryVC.sdTabbarItem = item3;

    SDTabbarItem *item4 = [[SDTabbarItem alloc] initWithTitle:@"我的" titleFont:titleFont image:[UIImage imageNamed:@"ic_tab_profile"] selectedImage:[UIImage imageNamed:@"ic_tab_profile_selected"] titleColor:titleColor selectedTitleColor:selectedColor badgeColor:badgeColor];
    item4.identifier = @"mine";
    self.mineVC.sdTabbarItem = item4;

    self.tabViewControllers = @[conversationNav,addressBookNav,coinNav,mineNav];
        
    [self updateThemeConfig];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)clearBadgeNumber {
    self.conversationVC.sdTabbarItem.badge = nil;
    self.addressBookVC.sdTabbarItem.badge = nil;
    self.discoveryVC.sdTabbarItem.badge = nil;
    self.mineVC.sdTabbarItem.badge = nil;
}

- (void)reset {
    [super reset];
}

- (void)updateThemeConfig {
    //主题,可以更改tabbar样式
    SDAppThemeConfigViewModel *themeConfigViewModel = [SDAppThemeManager shareInstance].configViewModel;
    
    UIImage *backgroundImage;
    if (themeConfigViewModel.tabbar.t_backgroundImage) {
        backgroundImage = themeConfigViewModel.tabbar.t_backgroundImage;
    } else {
        NSString *bgColor = themeConfigViewModel.tabbar.backgroundColor;
        backgroundImage = [UIImage imageWithColor:[UIColor colorWithHexString:bgColor] size:CGSizeMake(20.0, 20.0)];
        backgroundImage = [backgroundImage stretchableImageWithLeftCapWidth:backgroundImage.leftCapWidth*0.5 topCapHeight:backgroundImage.topCapHeight*0.5];
    }
    
    self.sdTabbar.bgroundImage = backgroundImage;
    
    NSString *showLine = themeConfigViewModel.tabbar.showLine;
    self.sdTabbar.showLine = [showLine boolValue];
    self.sdTabbar.lineColor = [UIColor colorWithHexString:themeConfigViewModel.tabbar.lineColor];
    
    UIColor *badgeBGColor = [UIColor colorWithHexString:themeConfigViewModel.tabbar.badgeBgColor];

    SDTabbarItem *homeItem = [self themeTabbarItem:themeConfigViewModel.tabbar.lianlian];
    homeItem.identifier = @"home";
    homeItem.badgeColor = badgeBGColor;
    
    SDTabbarItem *addressbookItem = [self themeTabbarItem:themeConfigViewModel.tabbar.message];
    addressbookItem.identifier = @"addressbook";
    addressbookItem.badgeColor = badgeBGColor;

    SDTabbarItem *discoveryItem = [self themeTabbarItem:themeConfigViewModel.tabbar.guangguang];
    discoveryItem.identifier = @"discovery";
    discoveryItem.badgeColor = badgeBGColor;

    SDTabbarItem *mineItem = [self themeTabbarItem:themeConfigViewModel.tabbar.mine];
    mineItem.identifier = @"mine";
    mineItem.badgeColor = badgeBGColor;

    [self.sdTabbar updateTabbarStyle:homeItem];
    [self.sdTabbar updateTabbarStyle:addressbookItem];
    [self.sdTabbar updateTabbarStyle:discoveryItem];
    [self.sdTabbar updateTabbarStyle:mineItem];
}

- (void)systemAppThemeChanged:(NSNotification *)notification {
    [self updateThemeConfig];
}

- (void)showTabBar:(BOOL)show {
    if (show != self.tabBar.hidden) {
        return;
    }
    
    UIView *subview= [self.view.subviews objectAtIndex:0];
    CGRect frame = subview.frame;
    CGRect tabBarFrame = self.tabBar.frame;
    
    if (show) {
        frame.size.height = kScreenHeight - self.tabBar.frame.size.height;
        tabBarFrame.origin.y = kScreenHeight - self.tabBar.frame.size.height;
    } else {
        frame.size.height = kScreenHeight;
        tabBarFrame.origin.y = kScreenHeight;
    }
    subview.frame = frame;
    self.tabBar.frame = tabBarFrame;
    self.tabBar.hidden = !show;
}

- (SDTabbarItem *)themeTabbarItem:(SDAppThemeConfigTabItemViewModel *)itemViewModel {
    SDTabbarItem *tabbarItem = [[SDTabbarItem alloc] init];
    tabbarItem.title = itemViewModel.title;
    tabbarItem.titleColor = [UIColor colorWithHexString:itemViewModel.titleColor];
    tabbarItem.selectedTitleColor = [UIColor colorWithHexString:itemViewModel.selectedTitleColor];
    tabbarItem.image = itemViewModel.t_icon;
    tabbarItem.selectedImage = itemViewModel.t_selectedIcon;
    return tabbarItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

这里的updateThemeConfig更改tabbar主题样式实现可以参考

https://blog.csdn.net/gloryFlow/article/details/132010193

六、小结

iOS开发-自定义Tabbar按钮Badge角标。Tabbar是放在APP底部的控件。UITabbarController是一个非常常见的一种展示模式了。比如微信、QQ都是使用tabbar来进行功能分类的管理。分别实现对应按钮、badge等

学习记录,每天不停进步。

你可能感兴趣的:(移动开发,iphone开发,Objective-c,ios,cocoa,macos,自定义Tabbar,badge)