5

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

4

2 回答 2

10

通过UITabBarController创建 UITabBar 非常简单。以下示例应在您的 AppDelegate 类中工作。

应用代理接口

首先,在界面中,我们将定义我们的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]];    

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

查看控制器实现

在每个视图控制器中,您还需要在 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"];
于 2011-05-07T10:04:19.340 回答
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];
于 2011-05-07T09:52:52.127 回答