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

news2025/1/21 15:32:04

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

Tabbar是放在APP底部的控件。UITabbarController是一个非常常见的一种展示模式了。比如微信、QQ都是使用tabbar来进行功能分类的管理。
在这里插入图片描述

一、实现自定义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等

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/812949.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Redis系列 2- Redis 的持久化

Redis系列 2- Redis 的持久化 1、关于 Redis 持久化2、RDB 持久化2.1、RDB 文件的创建与载入2.2、RDB 自动间隔性保存的配置2.3、Redis 快照2.4、RDB 重点总结 3、AOF 持久化3.1、命令追加(append)3.2、AOF 文件的写入与同步3.3、AOF 工作原理3.4、AOF 的文件载入与数据还原3.5…

QGIS3.28的二次开发一:编译工程

环境&#xff1a;VS2019OSGeo4WCMake_3.26Cygwin64QGIS_3.28 注意&#xff1a;一定要按照步骤顺序来&#xff01; 一、配置环境 &#xff08;一&#xff09;VS2019 VS2019下载链接https://my.visualstudio.com/Downloads?qvisual%20studio%202019&wt.mc_ido~msft~vsco…

day50-Insect Catch Game(捉虫游戏)

50 天学习 50 个项目 - HTMLCSS and JavaScript day50-Insect Catch Game&#xff08;捉虫游戏&#xff09; 效果 index.html <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta name"viewport"…

基于SpringBoot+Vue的大学生租房系统设计与实现(源码+LW+部署文档等)

博主介绍&#xff1a; 大家好&#xff0c;我是一名在Java圈混迹十余年的程序员&#xff0c;精通Java编程语言&#xff0c;同时也熟练掌握微信小程序、Python和Android等技术&#xff0c;能够为大家提供全方位的技术支持和交流。 我擅长在JavaWeb、SSH、SSM、SpringBoot等框架…

第 356 场力扣周赛题解

A 满足目标工作时长的员工数目 签到题 class Solution { public:int numberOfEmployeesWhoMetTarget(vector<int> &hours, int target) {int res 0;for (auto x: hours)if (x > target)res;return res;} };B 统计完全子数组的数目 枚举子数组&#xff1a;枚举子数…

小研究 - 主动式微服务细粒度弹性缩放算法研究(四)

微服务架构已成为云数据中心的基本服务架构。但目前关于微服务系统弹性缩放的研究大多是基于服务或实例级别的水平缩放&#xff0c;忽略了能够充分利用单台服务器资源的细粒度垂直缩放&#xff0c;从而导致资源浪费。为此&#xff0c;本文设计了主动式微服务细粒度弹性缩放算法…

溟㠭篆刻艺术……“瀚1”

每个人生犹如一颗颗繁星&#xff0c;在时空交错中汇聚成一条星汉灿烂的银河&#xff0c;在静谧深邃的宇宙中清澈回响&#xff0c;熠熠生辉。妻晓蕾题注溟㠭刊…… 溟㠭 篆刻作品“瀚1” 溟㠭 篆刻作品“瀚1” 溟㠭 篆刻作品“瀚1” 文/晓蕾

质效卓越,科技前沿—QECon北京站线下盛会成功落幕

7月28日-29日&#xff0c;第八届QECon质量效能大会在北京成功召开&#xff0c;这是质量效能领域备受期待的一场盛会&#xff0c;从2020年第一届QECon开启以来&#xff0c;历经四年QECon北京站终于首次线下落地。本次大会的核心主旨为“数生智慧&#xff0c;高质量发展新引擎”&…

虚拟局域网VLAN

概述 广播域 使用一个或多个以太网交换机互连接起来的交互式以太网&#xff0c;其所有站点都属于同一个广播域&#xff0c;随着交换式以太网规模的扩大&#xff0c;广播域响应扩大&#xff0c;从而形成一个巨大的广播域。 但是巨大的广播域会带来很多的弊端&#xff1a; 广…

JUC中其他常用类

1.CopyOnWriteArrayList ArrayList是线程不安全的&#xff0c;Vector是线程安全的(方法被Synchronized修饰)&#xff0c;CopyOnWriterArrayList是在Vector的基础上再做优化&#xff0c;因为当读取操作较多时&#xff0c;Vector的效率不高。CopyOnWriterArrayList中读操作并没有…

C++ 类和对象篇(一) 类的引入

目录 一、类的概念 二、类的引入 三、类的定义 1.定义一个类 2.struct 和 class 的区别 3.类中成员函数的声明、实现分离 四、封装及类的访问限定符 1.封装 2.类的访问限定符 五、类的作用域和生命周期 六、类的实例化 七、类存储方法 八、计算类的大小 一、类的概念 1…

Gazebo打不开

问题&#xff1a;启动Gazebo半天打不开&#xff0c;无反应 原因&#xff1a;启动Gazebo&#xff0c;会优先从网络上下载模型 解决方案&#xff1a; 1.断网&#xff0c;然后再启动Gazebo 2.把模型下载下来 模型下载链接&#xff1a;GitHub - osrf/gazebo_models: Gazebo da…

简要理清计算机的发展(从硬件和软件)

1.计算机硬件和其他板块的关系 2.什么是计算机系统 可以简单理解计算机系统 硬件 软件。 3.硬件、软件的发展 3.1.硬件发展 逻辑元件的发展&#xff1a; 发展时间逻辑原件速度&#xff08;次/秒&#xff09;内存外存其他第一代1946-1957电子管几千-几万汞延迟线、磁鼓穿…

从源程序到可执行文件的四个过程

从源程序到可执行文件的四个过程 预处理编译汇编链接 程序要运行起来&#xff0c;必须要经过四个步骤&#xff1a;预处理、编译、汇编和链接&#xff0c;如下图所示&#xff1a; -E选项&#xff1a;提示编译器执行完预处理就停下来&#xff0c;后边的编译、汇编、链接就先不执…

Flowable基础

简介 Flowable 是 BPMN 的一个基于 java 的软件实现&#xff0c;不过 Flowable 不仅仅包括 BPMN &#xff0c;还有 DMN 决策表和 CMMN Case 管理引擎&#xff0c;并且有自己的用户管理、微服务 API 等一系列功能&#xff0c; 是一个服务平台。 官方手册&#xff1a; https://…

百万数据快速导入导出

百万数据快速导入 pom <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.2.0</version></dependency>Resourceprivate SalariesListener salariesListener;private ExecutorService…

01-微信小程序开发准备

文章目录 小程序的特点微信小程序开发小程序注册一些基础的设置查看日志开发设置&#xff08;AppID小程序ID&#xff09;服务器域名接口设置 开发者工具下载开发者工具安装开发者工具使用创建小程序 小程序的特点 小程序的特点 : ●小程序是一种不需要下载安装即可使用的应用,…

分享一个jquery重复绑定事件的问题

这篇文章主要分享一下前端在使用jQuery给元素绑定click事件时遇到的一点小问题。 今天在通过JS代码动态绑定元素的点击事件时遇到一点问题&#xff0c;如上图所示&#xff0c;需要实现动态控制低级内丹格子的解锁&#xff0c;每种宠物造型都有一个内丹数量。如图&#xff0c;忘…

快速学会MyBatis映射关系一对一

文章目录 映射关系一对一映射关系-官方文档映射关系1对1-基本介绍基本介绍注意细节 映射关系1 对1-映射方式映射方式配置Mapper.xml 的方式方式1方式2 注解的方式实现应用实例总结 映射关系一对一 映射关系-官方文档 文档地址: https://mybatis.org/mybatis-3/zh/sqlmap-xml.…