如何将ViewController添加到导航控制器,如果它包含一个TableView作为root?

时间:2011-01-25 03:01:09

标签: ios uinavigationcontroller tableview viewcontroller

我正在尝试将UIViewController(AddProjectViewController)添加到导航控制器(navigationController),其中tableView设置为root,但它不起作用。

这就是我设置文件的方式:http://d.pr/y8rt

代码在ProjectsController.m - 请帮助:(

1 个答案:

答案 0 :(得分:16)

好的,所以我先向你解释一下你做错了什么:

// You're not allocating the view here.
AddProjectViewController *nextController = addProjectViewController;
// When allocated correctly above, you can simple push the new controller into view
[self.navigationController pushViewController: (UIViewController *)addProjectViewController animated:YES];

推送的视图控制器将自动继承super(推送它的视图控制器)导航栏(这意味着您可以在子视图控制器中对self.navigationController进行调用,因为UINavigationController只是UIViewController的子类(因此是的UITableViewController)。

以下是您需要做的事情:

// Allocate AddProjectViewController
AddProjectViewController *addProjectViewController = [[AddProjectViewController alloc] init];
// Adds the above view controller to the stack and pushes it into view
[self.navigationController pushViewController:addProjectViewController animated:YES];
// We can release it again, because it's retained (and autoreleases in the stack). You can also choose to autorelease it when you allocate it in the first line of code, but make sure you don't call release on it then!
[addProjectViewController release];

但是,对于您要做的事情,以模态方式呈现视图控制器会更好,这意味着您必须将其保存在导航控制器中。方法如下:

// Allocate AddProjectViewController
AddProjectViewController *addProjectViewController = [[AddProjectViewController alloc] init];
// Create a navigation controller
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:addProjectViewController];
// Release the view controller that's now being retained by the navigation controller
[addProjectViewController release];
// Adds the above view controller to the stack and present it modally (slide from bottom)
[self presentModalViewController:navigationController animated:YES];
// Release the navigation controller since it's being retained in the navigation stack
[navigationController release];

请注意,您需要在AddProjectViewController类中创建UIBarButtonItems。

我已更新您的代码并在此处上传:http://dl.dropbox.com/u/5445727/Zum.zip

希望它有所帮助,您需要查看此处的评论,我没有将它们转移到您的项目中。祝你好运:)