iOS开发9:使用Tab Bar切换视图

上一篇文章提到了多视图程序中各个视图之间的切换,用的Tool Bar,说白了仍是根据触发事件使用代码改变Root View Controller中的Content View。此次,咱们仍是讲一讲切换视图,不过此次使用的是Tab Bar。app

此次要写的程序运行起来的效果是这样的:底部有几个图标,每一个图标对应一个视图。每点击一个图标,对应的视图就会打开。以下图,就是咱们作好的程序效果:ide

 

每一个Tab Bar有一个对应颜色的视图。code

为了搞清使用Tab Bar切换视图的原理,咱们仍是从Empty Application开始建立咱们的程序。事件

一、运行Xcode 4.2,新建一个Empty Application,名称为Tab Bar Application,其余设置以下图:it

二、为工程添加图标文件:io

这里要添加的图标文件是用来定制各Tab Bar的。首先新建一个Group,选择File — New — New Group,建立好后给新的Group重命名为Icons。而后,将准备好的四个图标文件拖到Group中,在弹出的窗口选择Copy items……(if needed),以下图:class

四、建立四个View Controller:原理

选中Tab Bar Application这个Group,而后选择File — New — New File,在弹出的窗口,左边选择Cocoa Touch,右边选择UIViewController subclass,以后选Next,在弹出的窗口中,输入名称BlueViewController,并选中With xib,以下图:程序

而后选择Next,选好位置,点击Create,这样就建立了一个ViewController。以一样的方式再建立三个,名称分别是GreenViewController,RedViewController,YellowViewController。方法

五、建立TabBarController.xib:

选中Tab Bar Application这个Group,而后选择File — New — New File,在弹出的窗口,左边选择User Interface,右边选择Empty:

而后点Next,在弹出的窗口输入名称TabBarController,选好位置后点击Create。

以后,在Group中点击TabBarController.xib,你会发现跟BlueViewController.xib不同,里边没有一个像View同样的窗口,不要着急,咱们拖一个Tab Bar Controller到里边:

六、在上图中选择File’s Owner,打开Identity Inspector,在Class一栏选择AppDelegate:

这样,咱们就能够从TabBarController.xib向AppDelegate建立OutLet映射了。

七、打开Assistant Editor,保证Assistant Editor中打开的是AppDelegate.h,在左边选中Tab Bar Controller,按住Control,往AppDelegate.h中建立映射:

而后在弹出的窗口输入rootController,点击Connect:

打开AppDelegate.m,在didFinishLaunchingWithOptions方法中添加代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    [[NSBundle mainBundle] loadNibNamed:@"TabBarController" owner:self options:nil]; 
    [self.window addSubview:self.rootController.view]; 
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

八、单击TabBarController.xib,拖两个Tab Bar Item到Tab Bar上:

九、选中第一个View Controller,在右边打开Identity Inspector,在Class中选择BlueViewController:

而后,打开Attribute,在NIB Name选择BlueViewController:

对其余的View Controller进行一样的操做,依次设成GreenViewController、RedViewController、YellowViewController。

十、设置Tab Bar图标和文字:

展开Blue View Controller,选中其中的Tab Bar Item,打开Attribute,以下图:

Badge属性:设置的文字将以红色图标形式显示出来,好比,这个Tab显示的是Mail视图,你能够用Badge显示有多少封未读邮件。

Identifier属性:这个属性对应的下拉菜单中,若是你选择的是否是Custom,好比是Favorite,那么这个Tab Bar的名称和图标就都设置好了。咱们这里选择Custom。

在Title输入Blue,在Image选择Blue.png。

对其余Tab Bar Item进行相似操做,这样以后,整个Tab Bar以下图所示:

十一、如今单击.xib,选中View,打开Attribute Inspector,将其背景颜色改为蓝色。而后,在Simulated Metrics中设置Bottom Bar为Tab Bar:

对GreenViewController、RedViewController和YellowViewController进行一样设置,不过背景颜色要设成与其名称相对应的。

十二、大功告成了,运行一下,看看效果吧:

 

相关文章
相关标签/搜索