UITabBarController(一)

本文简单介绍 iOS 中 UITabBarController 标签页视图控制器的使用方式。

UITabBarController 对象可以保存一组视图控制器,让用户轻松地在各个视图控制器上自由切换。此外 UITabBarController 对象还会在屏幕底部显示一个标签栏(tab bar),标签栏会有多个标签项(tab item),分别对应 UITabBarController 对象中所保存的每一个视图控制器。单击某个标签项,UITabBarController 对象就会显示该标签项所对应的视图控制器的视图。

下方的标签栏称为 UITabBar,如果 UITabBarController 有 4 个子视图控制器,那么 UITabBar 内部就会有 4 个 UITabBarButton 作为子控件与之对应。

子控制器数量最多不得超过 5 个,即 UITabBarItem 数量小于等于 5。

示例一:通过代码方式创建 UITabBarController,并在 UITabBarController 上添加两个视图控制器。

Demo 预览

第一页 第二页

说明:

  • 点击 TabBar 底部的 Home 按钮,显示第一个视图控制器;
  • 点击 TabBar 底部的 Second 按钮,显示第二个视图控制器。

文档组织结构

实现步骤

  1. 新建两个父类为 UIViewController 的带 xib 的视图控制器子类对象,FirstViewControllerSecondViewController,为方便标识,我们在每个视图控制器的 xib 页面上添加了一个 UILabel 标签。
  2. 修改 SceneDelegate.m 文件,创建 UITabBarController 对象,将初始化好的两个视图控制器传入 UITabBarController 对象的 viewControllers 数组。最后,将 UITabBarController 对象设置为应用窗口的根视图控制器。
#import "SceneDelegate.h"

// Controllers
#import "FirstViewController.h"
#import "SecondViewController.h"

@interface SceneDelegate ()

// 添加选项卡控制器属性,作为容器包含两个视图控制器
@property (strong, nonatomic) UITabBarController *tabBarController;

@end

@implementation SceneDelegate

- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    
    // 创建 Window 对象
    self.window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];
    self.window.backgroundColor = [UIColor purpleColor];
    
    // 实例化视图控制器对象
    FirstViewController *firstViewController = [[FirstViewController alloc] init];
    SecondViewController *secondViewController = [[SecondViewController alloc] init];
    
    // 初始化选项卡视图控制器
    self.tabBarController = [[UITabBarController alloc] init];
    
    // 将两个视图控制器以数组的式指定给选项卡视图控制器
    // 使应用能够在两个视图控制器的对象之间自由的切换
    NSArray *array = [NSArray arrayWithObjects:firstViewController,secondViewController, nil];
    self.tabBarController.viewControllers = array;
    
    // 设置选项卡视图控制器为当前窗口的根视图控制器
    self.window.rootViewController  = self.tabBarController;
    
    // 设置 Window 为主窗口并显示
    [self.window makeKeyAndVisible];
}

注:在 Xcode 11 之前,自定义 UIWindow 相关的代码是在 AppDelegate 中处理的,在 iOS 13 中,所有 UI 生命周期由 SceneDelegate 负责处理,详情可见:WWDC 2019: Optimizing App Launch

除了与以前版本一样,要删除 Main storyboard file base name 之外,还要在项目 Info.plist 中,删除 SceneDelegate 的 StoryboardName。

  1. 设置每个视图控制器标签的标题和图标。

分别在每个视图控制器的实现文件中覆写视图控制器的指定初始化方法,以设置当前视图控制器标签的标题和图标。

FirstViewController.m 文件:

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  if (self) {
      // 设置 tabBar 图标和字体
      self.tabBarItem.title = @"Home";
      self.tabBarItem.image = [UIImage imageNamed:@"home_normal"];
      self.tabBarItem.selectedImage = [UIImage imageNamed:@"home_selected"];
  }
  return self;
}

SecondViewController.m 文件:

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  if (self) {
      // 设置 tabBar 图标和字体
      self.tabBarItem.title = @"Second";
      self.tabBarItem.image = [UIImage imageNamed:@"second_normal"];
      self.tabBarItem.selectedImage = [UIImage imageNamed:@"second_selected"];
  }
  return self;
}

示例二:自定义 UITabBarController 子类对象

创建一个 UITabBarController 子类对象作为基类,优点就是所有子视图控制器的标签项可以集中在该子类文件中设置,不必分散在各个视图控制器实现文件中。

💡TabBarController 和各视图控制器之间可以通过 StoryBoard 的方式连接。

Demo 预览

代码实现

// 注:kScreenWidth、kScreenHeight 两个宏定义来自 YYKit 框架
- (instancetype)init {
    self = [super init];
    if (self) {
        // 设置背景颜色和大小
        self.view.backgroundColor = COLOR_BACKGROUND;
        self.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        
        [self setViewControllers];
    }
    return self;
}

/*
 * 视图堆栈结构:
 * UITabBarController - UINavigationController - UIViewController (首页)
 *                    - UINavigationController - UIViewController (资讯)
 *                    - UINavigationController - UIViewController (我的)
 *
 */
- (void)setViewControllers {
    // 首页 TabBar
    UIViewController *mainViewController = [self renderTabBarItem:[[HQLMainViewController alloc] init] title:@"首页" imageNamed:@"tab_home_normal" selectedImageNamed:@"tab_home_selected"];
    HQLNavigationController *mainNavigationController = [[HQLNavigationController alloc] initWithRootViewController:mainViewController];
    
    // 资讯 TabBar
    UIViewController *secondViewController = [self renderTabBarItem:[[HQLSecondViewController alloc] init] title:@"资讯" imageNamed:@"tab_news_normal" selectedImageNamed:@"tab_news_selected"];
    HQLNavigationController *secondNavigationController = [[HQLNavigationController alloc] initWithRootViewController:secondViewController];
    
    // 我的 Tabbar
    UIViewController *thirdViewController = [self renderTabBarItem:[[HQLThirdViewController alloc] initWithStyle:UITableViewStyleGrouped] title:@"我的" imageNamed:@"tab_mine_normal" selectedImageNamed:@"tab_mine_selected"];
    HQLNavigationController *thirdNavigationController = [[HQLNavigationController alloc] initWithRootViewController:thirdViewController];
    
    self.viewControllers = @[mainNavigationController,secondNavigationController,thirdNavigationController];
}

- (UIViewController *)renderTabBarItem:(UIViewController *)viewController
                                 title:(NSString *)title
                            imageNamed:(NSString *)normalImgName
                    selectedImageNamed:(NSString *)selectedImgName {
    
    // 设置导航栏的标题为 TabBar 标题
    viewController.title = title;
    
    // 设置导航栏 TabBar
    UIImage *normalImage = [[UIImage imageNamed:normalImgName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *selectedImage = [[UIImage imageNamed:selectedImgName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:normalImage selectedImage:selectedImage];
    // 设置导航栏被选中时的字体
    [viewController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: COLOR_THEME}
                                             forState:UIControlStateSelected];
    return viewController;
}

其他属性设置

去掉TabBar上部的黑色线条,设置 TabBar 透明背景

// 注:imageWithColor: 方法来自 YYKit 框架
[[UITabBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]]];
[[UITabBar appearance] setShadowImage:[UIImage new]];

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

推荐阅读更多精彩内容