1. 程式人生 > >iOS開發UI篇—UITabBarController簡單介紹

iOS開發UI篇—UITabBarController簡單介紹

gif 什麽 div ins 簡單介紹 out hit cati create

一、簡單介紹

UITabBarController和UINavigationController類似,UITabBarController也可以輕松地管理多個控制器,輕松完成控制器之間的切換,典型的例子就是QQ、微信等應?。

技術分享圖片

二、UITabBarController的使用

1.使用步驟:

(1)初始化UITabBarController

(2)設置UIWindow的rootViewController為UITabBarController

(3)創建相應的子控制器(viewcontroller)

(4)把子控制器添加到UITabBarController

2.代碼示例

新建一個空的文件,在Application的代理中編碼

YYAppDelegate.m文件

技術分享圖片

//
// YYAppDelegate.m
// 01-UITabBar控制器基本使用
//
// Created by 孔醫己 on 14-6-7.
// Copyright (c) 2014年 itcast. All rights reserved.
//

#import "YYAppDelegate.h"

@implementation YYAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//1.創建Window
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];

//a.初始化一個tabBar控制器
UITabBarController *tb=[[UITabBarController alloc]init];
//設置控制器為Window的根控制器
self.window.rootViewController=tb;

//b.創建子控制器
UIViewController *c1=[[UIViewController alloc]init];
c1.view.backgroundColor=[UIColor grayColor];
c1.view.backgroundColor=[UIColor greenColor];
c1.tabBarItem.title=@"消息";
c1.tabBarItem.image=[UIImage imageNamed:@"tab_recent_nor"];
c1.tabBarItem.badgeValue=@"123";

UIViewController *c2=[[UIViewController alloc]init];
c2.view.backgroundColor=[UIColor brownColor];
c2.tabBarItem.title=@"聯系人";
c2.tabBarItem.image=[UIImage imageNamed:@"tab_buddy_nor"];

UIViewController *c3=[[UIViewController alloc]init];
c3.tabBarItem.title=@"動態";
c3.tabBarItem.image=[UIImage imageNamed:@"tab_qworld_nor"];

UIViewController *c4=[[UIViewController alloc]init];
c4.tabBarItem.title=@"設置";
c4.tabBarItem.image=[UIImage imageNamed:@"tab_me_nor"];


//c.添加子控制器到ITabBarController中
//c.1第一種方式
// [tb addChildViewController:c1];
// [tb addChildViewController:c2];

//c.2第二種方式
tb.viewControllers=@[c1,c2,c3,c4];


//2.設置Window為主窗口並顯示出來
[self.window makeKeyAndVisible];
return YES;
}

@end

技術分享圖片

實現效果:

技術分享圖片

三、重要說明

1.UITabBar

下方的工具條稱為UITabBar ,如果UITabBarController有N個子控制器,那麽UITabBar內部就會有N 個UITabBarButton作為子控件與之對應。

註意:UITabBarButton在UITabBar中得位置是均分的,UITabBar的高度為49。

在上面的程序中,UITabBarController有4個子控制器,所以UITabBar中有4個UITabBarButton,UITabBar的結構?大致如下圖所示:

技術分享圖片

2.UITabBarButton

UITabBarButton?面顯?什麽內容,由對應子控制器的tabBarItem屬性來決定

c1.tabBarItem.title=@"消息";
 c1.tabBarItem.image=[UIImage imageNamed:@"tab_recent_nor"];

技術分享圖片

3.有兩種方式可以往UITabBarController中添加子控制器

(1)[tb addChildViewController:c1];

(2)tb.viewControllers=@[c1,c2,c3,c4];

註意:展示的順序和添加的順序一致,和導航控制器中不同,展現在眼前的是第一個添加的控制器對應的View。

iOS開發UI篇—UITabBarController簡單介紹