编辑
这个答案已经过时。将视图控制器的视图添加为另一个视图控制器的子视图的正确方法是实现一个容器视图控制器。
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
属性设置为零。
这是一些快速伪代码。我以最低限度作为例子。
// 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
有点困惑,你问如何添加一个'UITableViewController'或如何设置单元格的内容为'UITableView'? – Steven
如何添加UITableViewController ...如果我成功地做到了这一点我认为我将能够处理单元格内容 – Vad
@Vad:你在使用故事板吗? – GeneralMike