如何在iOS上通过编程方式创建选项卡视图

5

如何在iPhone应用中以编程方式创建选项卡视图,最好使用Objective-C?

2个回答

10

通过UITabBarController非常简单地创建一个UITabBar。以下示例应该适用于您的AppDelegate类。

App Delegate Interface

首先,在接口中,我们将定义我们的UITabBarController

UITabBarController *tabBarController;

应用委托实现

然后,在实现文件的application:didFinishLaunchingWithOptions:方法中,我们初始化选项卡栏控制器。

// Initialise our tab bar controller
UITabBarController *tabBarController = [[UITabBarController alloc] init];

接下来,您需要创建要添加到标签栏控制器中的视图控制器。我们需要添加一些信息来设置标签的标题/图标,但我将在最后回到这个问题。

// Create your various view controllers
UIViewController *testVC = [[TestViewController alloc] init];
UIViewController *otherVC = [[OtherViewController alloc] init];
UIViewController *configVC = [[ConfigViewController alloc] init];

由于setViewControllers:animated:方法需要一个视图控制器数组,因此我们将把视图控制器添加到一个数组中,然后释放它们。(因为NSArray会保留它们。)

// Put them in an array
NSArray *viewControllers = [NSArray arrayWithObjects:testVC, otherVC, configVC, nil];
[testVC release];
[otherVC release];
[configVC release];

然后只需将包含视图控制器数组的UITabBarController提供给我们的窗口,即可完成添加。

// Attach them to the tab bar controller
[tabBarController setViewControllers:viewControllers animated:NO];

// Put the tabBarController's view on the window.
[window addSubview:[tabBarController view]];    

最后,确保在dealloc方法中调用[tabBarController release];

视图控制器实现

在每个视图控制器内部,您还需要在init方法中设置选项卡的标题和图标,如下所示:

// Create our tab bar item
UITabBarItem *tabBarItem = [self tabBarItem];
UIImage *tabBarImage = [UIImage imageNamed:@"YOUR_IMAGE_NAME.png"];
[tabBarItem setImage:tabBarImage];
[tabBarItem setTitle:@"YOUR TITLE"];

当我通过编程方式创建自己的tabBarControllers时,我总是为每个选项卡创建一个navigationController,并且每个navigationController都使用rootViewController进行初始化。在您的示例中,似乎不可能创建导航堆栈,因为您没有navigationController,但我从未尝试过这样编码。 - Wolfgang Schreurs
@Wolfgang 我想这取决于您是否希望将项目推入/弹出导航堆栈。(我的例子是一个相当基本的“仅基础”方法。) - John Parker
@Kiran 没问题 - 希望一切顺利。 :-) - John Parker

0

这是我们如何以编程方式创建选项卡栏

UINavigationController *BandNavigationController3;
AudienceSettingsViewController *audienceSettingsViewView =[[AudienceSettingsViewController alloc]initWithNibName:@"AudienceSettingsViewController" bundle:nil];
BandNavigationController3 = [[UINavigationController alloc]initWithRootViewController:audienceSettingsViewView];
BandNavigationController3.tabBarItem.title = @"Settings";
BandNavigationController3.tabBarItem.image = [UIImage imageNamed:@"settings.png"];

[BandNavigationController3.tabBarItem initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:4];
BandNavigationController3.navigationBar.hidden = YES;

[bandTabBarArray addObject:BandNavigationController3];
[BandNavigationController3 release];
[audienceSettingsViewView release];

[tabBarController setViewControllers:bandTabBarArray]; 
[bandTabBarArray release];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接