以编程方式为ViewController创建选项卡栏

时间:2013-06-11 07:48:22

标签: iphone objective-c

我一直在以编程方式向我的视图控制器添加一个标签栏,因为有一个滚动视图我不能将它放在我的视图中间。我对如何添加它很困惑。是否需要在我的ViewDidLoad方法或我的AppDelegate中启动? 如果我有:

UITabBarController  *tabBar = [[UITabBarController alloc] init];
[self.view addSubview:tabBar.view];
[tabBar release]; 

如何将其分配到scrollview的底部?

谢谢!

现在在我的appDelegate类中:

     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

   self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UITabBarController *tabBarController = [[UITabBarController alloc] init];

    ViewController* vc = [[ViewController alloc] init];


    NSArray* controllers = [NSArray arrayWithObjects:vc, tabBarController, nil];
    tabBarController.viewControllers = controllers;

    [_window addSubview:tabBarController.view];

   self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
   return YES;

}

它崩溃了,不确定它是否是我失踪的版本。

修改 对于其他人在Appdelegate.m中想知道这个:

self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = @[viewController1, viewController2, viewController3, viewController4];

3 个答案:

答案 0 :(得分:8)

请查看Apple提供的此文档:ViewControllers

示例代码:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
   UITabBarController *tabBarController = [[UITabBarController alloc] init];

   FirstViewController* vc1 = [[FirstViewController alloc] init];
   SecondViewController* vc2 = [[SecondViewController alloc] init];

   NSArray* controllers = [NSArray arrayWithObjects:vc1, vc2, nil];
   tabBarController.viewControllers = controllers;

   // Add the tab bar controller's current view as a subview of the window
   [window addSubview:tabBarController.view];
}

答案 1 :(得分:3)

我是这样做的。我从我的App Delegate复制了它,它工作正常。基本上,您将视图控制器添加到选项卡栏,然后将选项卡栏添加到窗口的子视图中。

实例化实例

iVacationTabBar = [[UITabBarController alloc] init];

但是,您创建了视图/视图控制器:

 UINavigationController *rvc_tools = [[UINavigationController alloc] initWithRootViewController: vc_tools];
    UINavigationController *rvc_settings = [[UINavigationController alloc] initWithRootViewController: vc_settings];
    UINavigationController *rvc_about = [[UINavigationController alloc] initWithRootViewController: vc_about];
    UINavigationController *rvc_currentpage = [[UINavigationController alloc] initWithRootViewController: vc_currentpage];
    UINavigationController *rvc_backup = [[UINavigationController alloc] initWithRootViewController:vc_backup];

将控制器添加到阵列:

NSArray* controllers = [NSArray arrayWithObjects: rvc_currentpage,  rvc_tools,rvc_settings, rvc_backup, rvc_about, nil];

将视图控制器数组设置为标签栏:

[iVacationTabBar setViewControllers: controllers animated:NO];

将标签栏添加到窗口的子视图中。

[_window addSubview:iVacationTabBar.view];

答案 2 :(得分:0)

您无法在UITabbarController上添加UIViewController。相反,在ViewController上,您必须显示TabbarController,创建TabbarController,为其设置ViewController,然后将其添加到Window。< / p>