下面记一下怎样通过代码的方式为选项卡添加视图。
1、创建一个基于Empty Application的项目
2、创建两个新类,基类选择UIViewController,勾选With XIB for user interface分别命名为"OneController'和"TwoController",
3、分别更改OneController.xib和TwoController.xib文件的view背景颜色,便于区分
4、在AppDelegate.m文件中的 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ }函数做如下修改(记得导入OneController和TwoController的头文件)
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
- //将tabBar(选项卡)添加进来
- UITabBarController *tabBarController = [[[UITabBarController alloc] init] autorelease];
- //为选项卡添加子控制器
- OneController *one = [[[OneController alloc] init] autorelease];
- [tabBarController addChildViewController:one];
- TwoController *two = [[[TwoController alloc] init] autorelease];
- [tabBarController addChildViewController:two];
- self.window.rootViewController = tabBarController;
- [self.window makeKeyAndVisible];
- return YES;
- }
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];//将tabBar(选项卡)添加进来UITabBarController *tabBarController = [[[UITabBarController alloc] init] autorelease];//为选项卡添加子控制器OneController *one = [[[OneController alloc] init] autorelease];[tabBarController addChildViewController:one];TwoController *two = [[[TwoController alloc] init] autorelease];[tabBarController addChildViewController:two];self.window.rootViewController = tabBarController;[self.window makeKeyAndVisible];return YES;
}
运行效果如下:
];