UITabBarController简单介绍

UITabBarController是IOS中很常用的一个viewController,例如系统的闹钟程序、QQ、微信程序等。UITabBarController通常作为整个程序的rootViewController,而且不能添加到别的container viewController中。

一、简单介绍

UITabBarController和UINavigationController类似,UITabBarController也可以轻松地管理多个控制器,轻松完成控制器之间的切换。

二、UITabBarController的使用

1.使用步骤:

(1)初始化UITabBarController的对象

(2)设置UIWindow的rootViewController为UITabBarController

(3)创建相应的子控制器(viewcontroller)

(4)把子控制器添加到UITabBarController(或者通过UITabBarController的viewController属性将要显示的所有content viewcontroller添加到UITabBarController中)

下面看一个简单的例子:

 

#import "AppDelegate.h"
#import "ViewController.h"//子控制器
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //1.创建Window
    self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor=[UIColor redColor];
    //初始化一个UITabBarController
    UITabBarController *tab=[[UITabBarController alloc]init];
    //设置控制器为Window的根控制器
    self.window.rootViewController=tab;
     //b.创建子控制器
    //用法和导航控制器一致
    ViewController *vc1=[[ViewController alloc]init];
    vc1.view.backgroundColor=[UIColor grayColor];
    vc1.title=@"vc1";
    //vc1.tabBarItem=[[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1];//系统的形状会把title掩盖住,换成系统对应的title

//    vc1.tabBarItem=[[UITabBarItem alloc]initWithTitle:@"vc1" image:nil  selectedImage:1];//自定义的添加图片
    //vc1.tabBarItem.image=[UIImage imageNamed:@""];添加图片
    vc1.tabBarItem.badgeValue=[NSString stringWithFormat:@"%@",@"王艳辉"];
    ViewController *vc2=[[ViewController alloc]init];
    vc2.view.backgroundColor=[UIColor greenColor];
    vc2.title=@"vc2";
    
    ViewController *vc3=[[ViewController alloc]init];
    vc3.view.backgroundColor=[UIColor blueColor];
    vc3.title=@"vc3";
    ViewController *vc4=[[ViewController alloc]init];
    vc4.view.backgroundColor=[UIColor brownColor];
    vc4.title=@"vc4";
    
    //把子控制器添加到UITabBarController的两种方法
    //注意:展示的顺序和添加的顺序一致,和导航控制器中不同,展现在眼前的是第一个添加的控制器对应的View。
    //1.
    [tab addChildViewController:vc1];
    [tab addChildViewController:vc2];
    [tab addChildViewController:vc3];
    [tab addChildViewController:vc4];
    //2.
    tab.viewControllers=@[vc1,vc2,vc3,vc4];
//    UITabBarButton在UITabBar中得位置是均分的,UITabBar的高度为49。
    //如果UITabBarController有N个子控制器,那么UITabBar内部就会有N 个UITabBarButton作为子控件与之对应。
    //在上面的程序中,UITabBarController有4个子控制器,所以UITabBar中有4个UITabBarButton,vc1,vc2,vc3,vc4.
    [self.window makeKeyAndVisible];
    return YES;
}

 

posted on 2015-11-20 13:43  沙->仙人掌  阅读(115)  评论(0编辑  收藏  举报