0

我有一个基于导航控制器的应用程序。我决定在我的应用程序中使用标签栏。

当用户按下某个选项卡栏项目时,我想显示某个视图控制器 - 我希望在我的代码中以编程方式选择要显示的视图控制器。

我试图在 Interface Builder 中将导航控制器添加到我的选项卡栏中,但未调用其视图控制器的 viewWillAppear。

如何实现此功能?

4

1 回答 1

1

我不知道这是否是“正确的方式”,但这是我通常使用三个选项卡执行此操作的方式。

- (void)initControls {
    // Create the window.
    [self setWindow:[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]];

    // Create Tab Bar.
    tabCon = [[UITabBarController alloc] init];

    // Local array variable that holds the viewcontrollers.
    // Capacity corresponds to the number of VC's
    NSMutableArray *localVCArray = [[NSMutableArray alloc] initWithCapacity:3];

    MyFirstViewController *oneViewController = [[MyFirstViewController alloc] init];
    UINavigationController *oneNavCon = [[UINavigationController alloc] initWithRootViewController:oneViewController];
    [localVCArray addObject:oneNavCon];
    [oneViewController release];
    [oneNavCon release];

    MySecondViewController *twoViewController = [[MySecondViewController alloc] init];
    UINavigationController *twoNavCon = [[UINavigationController alloc] initWithRootViewController:twoViewController];
    [localVCArray addObject:twoNavCon];
    [twoViewController release];
    [twoNavCon release];

    MyThirdViewController *threeViewController = [[MyThirdViewController alloc] init];
    UINavigationController *threeNavCon = [[UINavigationController alloc] initWithRootViewController:threeViewController];
    [localVCArray addObject:threeNavCon];
    [threeViewController release];
    [threeNavCon release];

    // Set the tab bars array of view controllers to the localVCArray
    [[self tabCon] setViewControllers:localVCArray animated:YES];

    // Release the localVCArray, all of its contents are now retained by tabCon.
    [localVCArray release];

    // Add controls to window and show.
    [window addSubview:[tabCon view]];
    [window makeKeyAndVisible];
}

在每个 viewController 的 init 方法中,您可以执行以下操作:

[[self tabBarItem] setImage:[dataSource tabConImg]];
[[self tabBarItem] setTitle:[dataSource name]];
[[self navigationItem] setTitle:[dataSource navConName]];

设置标签栏中使用的图标、标签栏中的标题以及导航项的标题。

于 2009-05-09T12:59:23.683 回答