1

我想在 UIView 中显示 UITableViewController,我有一个解决方法,但我想了解它为什么会这样工作。

这是场景的样子: - 创建了一个新的单视图应用程序
- 在 IB 中向主视图添加了一个视图
- 为视图创建了一个出口:

@property (weak, nonatomic) IBOutlet UIView *placeholderView;


- 向项目添加了带有 XIB 的新 UITableViewController
- 将 numberOfSectionsInTableView 更改为返回 1,将 numberOfRowsInSection 更改为返回 10,并将 cellForRowAtIndexPath 更改为:

cell.textLabel.text = @"hello";


- 在 ViewController 文件中的 ViewDidLoad 方法:

ORGTableViewController *tableView = [[ORGTableViewController alloc] initWithNibName:@"ORGTableViewController" bundle:nil];

[self.placeholderView addSubview:tableView.tableView];

现在表格出现在 placeholderView 但它是空的。在 TableViewController 文件中调用 InitWithStyle 和 ViewDidLoad 方法。但是没有调用 numberOfSectionsInTableView、numberOfRowsInSection 和 cellForRowAtIndexPath。

还尝试在 AppDelegate 中将此代码添加到 didFinishLaunchingWithOptions 方法,并且它 -<em>按预期工作,出现带有文本的单元格:

ORGTableViewController *tableViewController = [[ORGTableViewController alloc] initWithNibName:@"ORGTableViewController" bundle:nil];

self.window.rootViewController = tableViewController;

所以它起作用了,当我将 UITableViewController 添加到 UIView 时,它看起来像委派搞砸了,解决方法很简单...... ViewController,viewDidLoad 方法:

ORGTableViewController *tableViewController = [[ORGTableViewController alloc] initWithNibName:@"ORGTableViewController" bundle:nil];
tableViewController.tableView.delegate = tableViewController;

[self.placeholderView addSubview:tableViewController.tableView];

你知道为什么委派会这样工作吗?

谢谢!

4

1 回答 1

2

你的问题本身就有答案。在第一个代码中,您没有像在第二个代码中那样设置删除,而是将委托设置为tableViewController.tableView.delegate = tableViewController;它将调用在tableViewController.

如果您打算在您的placeholderView类中实现委托方法,您需要将委托设置为`tableViewController.tableView.delegate = self;,然后在placeholderView类中实现所有委托。那会奏效的。

如果只需要一个UITableView,也可以考虑将该类子UITableView类化,添加为 的子视图placeholderView

于 2013-01-08T01:11:49.687 回答