如何在iPhone应用中以编程方式创建选项卡视图,最好使用Objective-C?
通过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"];
这是我们如何以编程方式创建选项卡栏
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];