开发环境:Xcode4.5
很多时候我们创建一个基于UITabBarController的application以后还希望能够在每个tab view都可以实现导航控制,即添加一个UINavigationController来实现tabview内部的view之间的切换,这即是本文所要介绍的。
一、创建一个 Tabbed Application.默认创建的是带有两个Tab的工程。
二、在AppDelegate.h里面添加
@property (strong, nonatomic) UINavigationController *NaviView1Controller;
@property (strong, nonatomic) UINavigationController *NaviView2Controller;
三、修改AppDelegate.m文件的didFinishLaunchingWithOptions函数,在这里我们设置相应的UINavigationController.
修改前:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
UIViewController *viewController1 = [[[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil] autorelease];
UIViewController *viewController2 = [[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = @[viewController1, viewController2];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
修改后:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
UIViewController *viewController1 = [[[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil] autorelease];
viewController1.title = @"View1";
self.NaviView1Controller = [[[UINavigationController alloc] initWithRootViewController:viewController1] autorelease];
UIViewController *viewController2 = [[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil] autorelease];
viewController2.title = @"View2";
self.NaviView2Controller = [[[UINavigationController alloc] initWithRootViewController:viewController2] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = @[self.NaviView1Controller, self.NaviView2Controller];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
运行一下程序,可以看到每个Tab view都自动多了一个NavigationBar在顶部。
三、添加两个新的View测试NavigationController。
1. 创建Test1ViewController类,以及对应的xib文件。
2. 创建Test2ViewController类,以及对应的xib文件。
3. 如果你的iPhone iOS版本低于6.0,在xib的设置里需要勾掉autolayout选项。
四、在Tab view 1的xib文件里添加一个按钮,并设置相应的IBOutlet, IBAction.如下图:
五、编写代码逻辑。
在FirstViewController.m中。编写函数gotoTest1View
- (IBAction)gotoTest1View:(id)sender {
Test1ViewController *SRDVController = [[Test1ViewController alloc]init];
[self.navigationController pushViewController:SRDVController animated:YES];
[SRDVController release];
}
同理可以测试,Test2ViewController.不再赘述。
六、代码下载:http://download.csdn.net/detail/lovefqing/4845092
若本文和代码有任何错误,欢迎拍砖指正!