问题描述
对于iPhone应用程序,我如何以编程方式(最好是在Objective-C中)创建选项卡视图?
For an iPhone app how can I create a tab view programmatically, preferably in Objective-C?
推荐答案
通过 UITabBarController .以下示例应在您的AppDelegate类中起作用.
It's quite simple to create a UITabBar via the UITabBarController. The following example should work within your AppDelegate class.
应用程序代理界面
首先,在界面中,我们将定义 UITabBarController .
Firstly, within the interface, we'll define our UITabBarController.
UITabBarController *tabBarController;
应用代理实现
然后,在实现文件的application:didFinishLaunchingWithOptions:
方法中,我们将初始化标签栏控制器.
Then, within the implementation file's application:didFinishLaunchingWithOptions:
method, we'll then initialise our tab bar controller.
// Initialise our tab bar controller
UITabBarController *tabBarController = [[UITabBarController alloc] init];
接下来,您需要创建要添加到选项卡栏控制器的视图控制器.我们需要在其中添加一些信息来设置标签的标题/图标,但最后我将再次介绍.
Next, you need to create the view controllers that you want to add to the tab bar controller. We'll need to add some information into these to set the tab's title/icon, but I'll come back to that at the end.
// Create your various view controllers
UIViewController *testVC = [[TestViewController alloc] init];
UIViewController *otherVC = [[OtherViewController alloc] init];
UIViewController *configVC = [[ConfigViewController alloc] init];
由于setViewControllers:animated:方法需要一个视图控制器数组,因此我们将视图控制器添加到数组中,然后释放它们. (因为NSarray将保留它们.)
As the setViewControllers:animated: method requires an array of view controllers, we'll add our view controllers to an array and then release them. (As the NSarray will retain them.)
// Put them in an array
NSArray *viewControllers = [NSArray arrayWithObjects:testVC, otherVC, configVC, nil];
[testVC release];
[otherVC release];
[configVC release];
然后只需为UITabBarController提供视图控制器数组并将其添加到我们的窗口中即可.
Then simply provide the UITabBarController with the array of view controllers and add it to our window.
// 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];
.
Finally, make sure you call [tabBarController release];
within your dealloc
method.
View Controller实施
在每个视图控制器中,您还需要按如下所示在init方法中设置选项卡的标题和图标:
Inside each of your view controllers, you'll also want to set the title and icon for the tab within the init method as follows:
// Create our tab bar item
UITabBarItem *tabBarItem = [self tabBarItem];
UIImage *tabBarImage = [UIImage imageNamed:@"YOUR_IMAGE_NAME.png"];
[tabBarItem setImage:tabBarImage];
[tabBarItem setTitle:@"YOUR TITLE"];
这篇关于如何在iOS上以编程方式创建选项卡视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!