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

时间:2011-05-07 09:48:32

标签: ios objective-c uitabview

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

2 个答案:

答案 0 :(得分:10)

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

App代理接口

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

答案 1 :(得分:-1)

这就是我们必须以编程方式创建tabbar的方法

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];