UITabBarController的使用详解及其自定义

简介

UITabBarController - 选项卡控制器,与导航控制器一样,也被广泛用于各种ios应用程序。顾名思义,选项卡控制器在屏幕底部显示一系列“选显卡”,这些选项卡表示为图标和文本,用户触摸它们将在不同的场景间切换。和UINavigationController类似,UITabBarController也可以用来控制多个页面导航,用户可以在多个视图控制器之间移动,并可以定制屏幕底部的选项卡栏。
借助屏幕底部的选项卡栏,UITabBarController不必像UINavigationController那样以栈的方式推入和推出视图,而是建立一系列的控制器(这些控制器可以是UIViewController、UINavigationController、UITableViewController等)并将它们添加到选项卡栏,使每个选项卡对应一个控制器。每个场景都呈现了应用程序的一项功能,或是提供了一种查看应用程序的独特方式。UITabBarController是iOS中很常用的一个viewController,例如系统的闹钟程序等,QQ也是用的UITabBarController。UITabBarController通常作为整个程序的rootViewController,而且不能添加到别的container viewController中。


UITabBarController的View层级图

与导航控制器一样,选项卡控制器会为我们处理一切。当用户触摸按钮时会在场景之间进行切换,我们无需以编程的方式处理选项卡栏事件,也无需手工在视图控制器之间切换。

UITabBarController的使用步骤

  • 初始化UITabBarController控制器
  • 设置UIwindow的rootViewController为这个UITabBarController
  • 在UITabBarController中添加子控制器

示例代码

#import "AppDelegate.h"


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    // 创建窗口
    self.window = [[UIWindow alloc]init];
    self.window.frame = [UIScreen mainScreen].bounds;
    
    
    // 设置窗口的跟控制器
    UITabBarController * tabbarVC = [[UITabBarController alloc]init];

    // 添加子控制器
    UIViewController * VC01 = [[UIViewController alloc]init];
    // 设置标题
    VC01.tabBarItem.title = @"精华";
    // 设置默认图片
    VC01.tabBarItem.image = [UIImage imageNamed:@"tabBar_essence_icon"];
    // 设置选中图片
    VC01.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_essence_click_icon"];
    VC01.view.backgroundColor = [UIColor yellowColor];
    [tabbarVC addChildViewController:VC01];
    
    UIViewController * VC02 = [[UIViewController alloc]init];
    VC02.tabBarItem.title = @"新帖";
    VC02.tabBarItem.image = [UIImage imageNamed:@"tabBar_new_icon"];
    VC02.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_new_click_icon"];
    VC02.view.backgroundColor = [UIColor redColor];
    [tabbarVC addChildViewController:VC02];
    
    UIViewController * VC03 = [[UIViewController alloc]init];
    VC03.tabBarItem.title = @"关注";
    VC03.tabBarItem.image = [UIImage imageNamed:@"tabBar_friendTrends_icon"];
    VC03.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_friendTrends_click_icon"];

    VC03.view.backgroundColor = [UIColor blueColor];
    [tabbarVC addChildViewController:VC03];
    
    UIViewController * VC04 = [[UIViewController alloc]init];
    VC04.tabBarItem.title = @"我";
    VC04.tabBarItem.image = [UIImage imageNamed:@"tabBar_me_icon"];
    VC04.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_me_click_icon"];

    VC04.view.backgroundColor = [UIColor greenColor];
    [tabbarVC addChildViewController:VC04];
    

    
    
    self.window.rootViewController = tabbarVC;
    
    // 显示窗口
    [self.window makeKeyAndVisible];
    
    return YES;
}
效果图

但是这样在appdelegate里面进行设置会有很多缺点:

  • 底部tabbaritem都是默认的蓝色
  • 添加子控制器的代码暴露在了外面

以自定义的方式实现UITabBarController

步骤:

  • 新建一个继承自UITabBarController的子类
  • 将这个子类设置为根控制器
  • 在这个子类里面实现添加子控制器的方法

但是在这种情况下因为有系统默认的蓝色渲染,会导致选中图标selectedImage不是图片原来的样子,可以通过以下两种方式解决:

  • 方法1:设置选中图片的渲染模式
    // 添加子控制器
    UIViewController * VC01 = [[UIViewController alloc]init];
    // 设置标题
    VC01.tabBarItem.title = @"精华";
    // 设置默认图片
    VC01.tabBarItem.image = [UIImage imageNamed:@"tabBar_essence_icon"];
    
    UIImage * image = [UIImage imageNamed:@"tabBar_essence_click_icon"];
    
    // 设置渲染模式 - 保持原始的渲染
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    // 设置选中图片
    VC01.tabBarItem.selectedImage =image;
    VC01.view.backgroundColor = [UIColor yellowColor];
    [self addChildViewController:VC01]
  • 方法2:直接在图片文件夹的属性里面进行设置 - 将render as设置成original image


由于文字和图片一样是默认的蓝色,所以也要进行设置才能达到自己想要的效果

方案一:通过setTitleTextAttributes属性设置(但是这个方法很麻烦,每次设置的时候都需要写很多代码)
- setTitleTextAttributes设置的时候是通过字典设置的,所以先搞一个字典

   // 添加子控制器
   UIViewController * VC01 = [[UIViewController alloc]init];
   // 设置标题
   VC01.tabBarItem.title = @"精华";
   // 设置默认图片   
   VC01.tabBarItem.image = [UIImage imageNamed:@"tabBar_essence_icon"];
   //设置选中图片
   VC01.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_essence_click_icon"];
   
   // 设置文字属性
   NSMutableDictionary * attrs = [NSMutableDictionary dictionary];
   attrs[NSFontAttributeName] = [UIFont systemFontOfSize:12.0];
   // 设置文字的前景色
   attrs[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
   
   [VC01.tabBarItem setTitleTextAttributes:attrs forState:UIControlStateNormal];
   
   VC01.view.backgroundColor = [UIColor yellowColor];
   [self addChildViewController:VC01];

优化方案(appearance)

  • 由于文字属性每次设置的时候代码很多很烦,所以要进行简化
  • 当方法方法后面有UI_APPERANCE宏的时候,就可以通过appearance对象一次性设置
- (void)setTitleTextAttributes:(nullable NSDictionary<NSString *,id> *)attributes forState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
  • 步骤:
    • 拿到那个item的apperance
    • 对这个item进行设置、
    • 之后所有的item都会是这个属性
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 通过appearance统一设置UITabbarItem的文字属性
    NSMutableDictionary * attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:12.0];  // 设置文字大小
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];  // 设置文字的前景色
    
    NSMutableDictionary * selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSFontAttributeName] = attrs[NSFontAttributeName];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    
    UITabBarItem * item = [UITabBarItem appearance];  // 设置appearance
    [item setTitleTextAttributes:attrs forState:UIControlStateNormal];
    [item setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    
    
    // 添加子控制器
    UIViewController * VC01 = [[UIViewController alloc]init];
    // 设置标题
    VC01.tabBarItem.title = @"精华";
    // 设置默认图片   
    VC01.tabBarItem.image = [UIImage imageNamed:@"tabBar_essence_icon"];
    //设置选中图片
    VC01.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_essence_click_icon"];
    
    
    [VC01.tabBarItem setTitleTextAttributes:attrs forState:UIControlStateNormal];
    
    VC01.view.backgroundColor = [UIColor yellowColor];
    [self addChildViewController:VC01];
    
    UIViewController * VC02 = [[UIViewController alloc]init];
    VC02.tabBarItem.title = @"新帖";
    VC02.tabBarItem.image = [UIImage imageNamed:@"tabBar_new_icon"];
    VC02.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_new_click_icon"];
    VC02.view.backgroundColor = [UIColor redColor];
    [self addChildViewController:VC02];
    
    UIViewController * VC03 = [[UIViewController alloc]init];
    VC03.tabBarItem.title = @"关注";
    VC03.tabBarItem.image = [UIImage imageNamed:@"tabBar_friendTrends_icon"];
    VC03.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_friendTrends_click_icon"];
    VC03.view.backgroundColor = [UIColor blueColor];
    [self addChildViewController:VC03];
    
    UIViewController * VC04 = [[UIViewController alloc]init];
    VC04.tabBarItem.title = @"我";
    VC04.tabBarItem.image = [UIImage imageNamed:@"tabBar_me_icon"];
    VC04.tabBarItem.selectedImage = [UIImage imageNamed:@"tabBar_me_click_icon"];
    VC04.view.backgroundColor = [UIColor greenColor];
    [self addChildViewController:VC04];
}

封装 - 封装添加自定义子控制器的方法

  • 由于自定义子控制器的代码很相似,所以可以进行抽取
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 通过appearance统一设置UITabbarItem的文字属性
    NSMutableDictionary * attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:12.0];  // 设置文字大小
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];  // 设置文字的前景色
    
    NSMutableDictionary * selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSFontAttributeName] = attrs[NSFontAttributeName];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    
    UITabBarItem * item = [UITabBarItem appearance];  // 设置appearance
    [item setTitleTextAttributes:attrs forState:UIControlStateNormal];
    [item setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    
    // 添加子控制器
    [self setupChildVC:@"精华" andImage:@"tabBar_essence_icon" andSelectImage:@"tabBar_essence_click_icon"];
    [self setupChildVC:@"新帖" andImage:@"tabBar_new_icon" andSelectImage:@"tabBar_new_click_icon"];
    [self setupChildVC:@"关注" andImage:@"tabBar_friendTrends_icon" andSelectImage:@"tabBar_friendTrends_click_icon"];
    [self setupChildVC:@"我" andImage:@"tabBar_me_icon" andSelectImage:@"tabBar_me_click_icon"];
}

/**
 * 初始化子控制器
 */
- (void)setupChildVC:(NSString * )title andImage:(NSString * )image andSelectImage:(NSString *)selectImage{
    UIViewController * VC = [[UIViewController alloc]init];
    VC.tabBarItem.title = title;
    VC.tabBarItem.image = [UIImage imageNamed:image];
    VC.tabBarItem.selectedImage = [UIImage imageNamed:selectImage];
    VC.view.backgroundColor = [UIColor greenColor];
    [self addChildViewController:VC];
}

自定义底部tabbar样式

通过上面的方法设置之后tabbar的样式

如果想要在这个tabbar上面添加一个按钮(注意不是item,tabbaritem是图片在上,文字在下的格式),这个按钮和item样式不一样,占据了和item上文字加上图片的大小。由于添加到tabbar上面的item是从左到右顺序排列的,如果是直接添加一个item,那么不能达到我们想要的样式(当然,如果你是添加一个item的话,直接按照以前的方法就行了),这个时候可以通过自定义tabbar来实现。


想要实现的效果
  • 由于tabbar是read-only属性,所以只能通过KVC模式跟换tabbar

步骤:

  • 新建一个继承自UITabbar的类
  • 在这个类里面实现初始化
  • layoutSubviews方法里面重新布局
  • 在TabbarController里面跟换tabbar
  • 虽然我们在TabbarController里面换成了自定义的tabbar,但是因为这个tabbar继承自uitabbar,所以它原来的属性和内容还在
#import "LMHTabbar.h"

@interface LMHTabbar()
/** 发布按钮 */
@property (nonatomic, weak) UIButton * publishBtn;

@end

@implementation LMHTabbar

/**
 * 初始化
 */
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        // 设置tabbar的子控件
        UIButton * publishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [publishBtn setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [publishBtn setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        [publishBtn sizeToFit];
        
        [self addSubview:publishBtn];
        self.publishBtn = publishBtn;
    }
    return self;
}

/**
 * 重写布局子控件的方法进行布局
 */
- (void)layoutSubviews{
    [super layoutSubviews];
    
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    
    // 设置发布按钮的frame
    self.publishBtn.center = CGPointMake(width  * 0.5, height * 0.5);
    
    
    
    // 设置其他的UITabBar的frame
    CGFloat buttonY = 0;
    CGFloat buttonW = width /5;
    CGFloat buttonH = height;
    NSInteger index = 0;
    for (UIView  * button in self.subviews) {
        
        // 判断 - 只有是UITabBarButton的button才进行布局(也就是tabbar上面的精华、新帖、关注、我这四个按钮) 而发布按钮不是UITabBarButton,就不进行布局
        // 由于UITabBar是苹果官方私有的, 所以不能直接设置
        if (![button isKindOfClass:NSClassFromString(@"UITabBarButton")])  continue;
        
        //  计算按钮的x值
        CGFloat buttonX = buttonW * ((index > 1) ? (index + 1): (index));
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        // 索引增加
        index ++;
    }
    
    
}
@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容