1 前言
UITabBarController为多视图控制器,可以切换不同视图,今天我们来学习一下其简单用法。
2 代码实例
ZYViewController.h:
#import <UIKit/UIKit.h>
#import "ZYFirstViewController.h"
#import "ZYSecondViewController.h"
@interface ZYViewController : UIViewController
@property(nonatomic,strong) ZYFirstViewController *firstViewController;//第一个视图
@property(nonatomic,strong) ZYSecondViewController *secondViewController;//第二个视图
@property(nonatomic,strong) UITabBarController *taBarController;//多视图控制器
@property (strong,nonatomic) UINavigationController *firstnavigationController;//第一个视图导航栏
@property (strong,nonatomic) UINavigationController *secondnavigationController;//第二个视图导航栏
@end
ZYViewController.m:
@synthesize firstViewController;
@synthesize secondViewController;
@synthesize taBarController;
@synthesize firstnavigationController;
@synthesize secondnavigationController;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title = @"UITabBarControllerTest";
self.firstViewController = [[ZYFirstViewController alloc] initWithNibName:nil bundle:nil];
firstnavigationController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
self.secondViewController = [[ZYSecondViewController alloc] initWithNibName:nil bundle:nil];
secondnavigationController = [[UINavigationController alloc] initWithRootViewController:secondViewController];
NSArray *twoViewControllers = [[NSArray alloc] initWithObjects:firstnavigationController,secondnavigationController, nil];//实例化视图数组
self.taBarController = [[UITabBarController alloc] init];
[self.taBarController setViewControllers:twoViewControllers];
[self.view addSubview:taBarController.view];
}
ZYFirstViewController.m:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {//由于多视图控制器加载时候不会加载非首页面,所以把初始化放在该方法中
self.title = @"First";//设置标题,并会自动赋给多视图控制器按钮
self.tabBarItem.image = [UIImage imageNamed:@"first.png"];//添加图片
self.view.backgroundColor = [UIColor whiteColor];
}
return self;
}
ZYSecondViewController.m:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.title = @"Second";
self.tabBarItem.image = [UIImage imageNamed:@"second.png"];
self.view.backgroundColor = [UIColor whiteColor];
}
return self;
}
运行结果:
当单击Second时候:
3 结语
以上是UITabBarController的简单介绍,希望对大家有所帮助。
Demo实例下载地址:http://download.csdn.net/detail/u010013695/5293799