编辑
这个答案已经过时了。将视图控制器的视图添加为另一个视图控制器的子视图的正确方法是实现容器视图控制器。
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html
原始答案
你的模式有点与众不同。执行您所描述的操作的最常见方法是初始化并呈现 SecondViewController。如果这确实是您想要的,我强烈建议您仔细阅读 Apple 的文档,了解如何创建、自定义和呈现 UIViewController 和 UITableViewController。
如果您知道所有这些并且真的想要做一些自定义的事情,那么请继续阅读。
相反,您正在创建 SecondViewController 的实例,而不是呈现它,而是将其视图添加到当前视图控制器视图中。如果您知道自己想要完成什么并且这实际上是您想要的结果,那么就去做吧。
配置这种通用模式的方法不止一种。在这个例子中我会坚持最简单的方式。
1) MainViewController (MVC) 应该在需要时将 SecondViewController (SVC) 实例保留在属性中。
2) SVC 是UITableViewController 的子类,因此默认设置为dataSource 和delegate,因为它是UITableView。这意味着您需要在SVC 中实现UITableViewDataSource 和UITableViewDelegate 方法,以便为您的表填充数据。假设MVC 知道需要将哪些数据放入表中,它应该将其传递给SVC。最简单的方法是在SVC 上定义一个属性,该属性可以在初始化时在MVC 中设置。
3) 假设有一种方法可以在表格呈现后将其关闭,您会希望 MVC 这样做。基本上,MVC 会将SVC 的视图从其父视图中移除,然后将SVC 属性设置为nil。
这里有一些快速的伪代码。我写了最低限度的例子。
// MainViewController.h
//
#import "SecondViewController.h"
@interface MainViewController : UIViewController
@property (nonatomic, strong) SecondViewController *svc;
@end
// MainViewController.m
//
#import "MainViewController.h"
@implementation MainViewController
// init and configure views w/ init, loadView, viewDidLoad, etc
// present SecondViewController
- (void)presentSecondViewController:(id)sender {
self.svc = [[SecondViewController alloc] init];
// this example uses an array as the SVC data
self.svc.tableData = @[@"first", @"second", @"third", @"fourth"];
self.svc.view.frame = self.view.bounds;
[self.view addSubview:self.svc.view];
}
// dismiss SecondViewController
- (void)dismissSecondViewController:(id)sender {
if (self.svc) {
[self.svc.view removeFromSuperview];
self.svc = nil;
}
}
// SecondViewController.h
//
@interface SecondViewController : UITableViewController
@property (nonatomic, strong) NSArray *tableData;
@end
// SecondViewController.m
//
@implementation SecondViewController
// init and configure views w/ init, loadView, viewDidLoad, etc
// override tableData getter to create empty array if nil
- (NSArray *)tableData
{
if (!tableData) {
_tableData = @[];
}
return _tableData;
}
// override tableData setter to reload tableView
- (void)setTableData:(NSArray *)tableData
{
_tableData = tableData;
[self.tableView reloadData];
}
// implement UITableViewDelegate and UITableViewDataSource methods using
// the self.tableData array