您应该将UINavigationController 实例添加到UITabBarController,然后将表格视图控制器添加到UINavigationController 实例的rootViewController 属性,这应该会让您的生活更轻松。
作为一个简单的例子,创建一个空的基于窗口的应用程序(模板使这比实际情况更令人困惑)。
将您的 UIViewController/UITableViewController 子类添加到项目中,然后使用此代码作为设置项目的指南。此代码在您的 AppDelegate 类中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// create our table view controller that will display our store list
StoresViewController *storeListController = [[StoresViewController alloc] init];
// create the navigation controller that will hold our store list and detail view controllers and set the store list as the root view controller
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:storeListController];
[navController.tabBarItem setTitle:@"TableView"];
[navController.tabBarItem setImage:[UIImage imageNamed:@"cart.png"]];
// create our browser view controller
BrowserViewController *webBrowserController = [[BrowserViewController alloc] init];
[webBrowserController.tabBarItem setTitle:@"WebView"];
[webBrowserController.tabBarItem setImage:[UIImage imageNamed:@"web.png"]];
// add our view controllers to an array, which will retain them
NSArray *viewControllers = [NSArray arrayWithObjects:navController, webBrowserController, nil];
// release these since they are now retained
[navController release];
[storeListController release];
[webBrowserController release];
// add our array of controllers to the tab bar controller
UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:viewControllers];
// set the tab bar controller as our root view controller
[self.window setRootViewController:tabBarController];
// we can release this now since the window is retaining it
[tabBarController release];
[self.window makeKeyAndVisible];
return YES;
}
在上面的代码示例中,BrowserViewController 是 UIViewController 的子类,StoresViewController 类是 UITableViewController 的子类。 UITabBarController 和 UINavigationController 实例以编程方式创建并添加到窗口中。
通过继承 UITableViewController 类,您可以避免以编程方式创建 UITableView 实例并获得开箱即用的大部分所需内容。
当您需要将详细视图推送到 UINavigationController 实例的堆栈中时,您只需使用类似于此的内容:
[self.navigationController pushViewController:YourDetailViewControllerInstance animated:YES];
这将为您将详细视图 UIViewController 子类添加到 UINavigationController 实例的视图层次结构中并为过渡设置动画。
其中有很多控制器,但这是完全值得的,并且会避免您遇到的很多问题,因为这种方法允许视图管理调整大小并自行考虑工具栏/导航栏。