2

我正在尝试使用情节提要添加子视图。它显示正确,但子视图中没有按钮 ( IBAction) 可以正常工作,即使使用空代码,单击时应用程序总是崩溃。

表视图控制器.m

...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Load SubView    
    SubviewViewController *subview = [self.storyboard instantiateViewControllerWithIdentifier:@"SubviewViewController"];
    [self.view addSubview:subview.view];
}
...

子视图控制器.m

- (IBAction)btnCloseSubview:(id)sender
{
    // Crashes the app when clicked, even empty as it's. 
}
4

2 回答 2

5

You shouldn't just add another view controller's view to your view like that, it can get you into trouble. When I've tried that, it sometimes works and sometimes not. The proper way is to also add the controller as a child view controller of TableViewController:

SubviewViewController *subview = [self.storyboard instantiateViewControllerWithIdentifier:@"SubviewViewController"];
[self addChildViewController: subview];
[subview didMoveToParentViewController:self];
[self.view addSubview:subview.view];

You probably need to set the frame of subview's view as well (subview.view.frame = self.view.bounds if you want it to be the same size).

As an alternative, you could create a view, not a view controller, in a xib file, and add that as a subview of your view. In that case, you would set the file's owner of the xib to TableViewController, and put the button's method in TableViewController.

于 2013-05-14T03:20:14.017 回答
2

查看 UIContainerView,它处理子视图控制器。您将需要自己处理父视图控制器和子视图控制器之间的通信,但除此之外,只要您的子视图在带有它的视图控制器的故事板。

查看有关容器视图的更深入信息。

于 2013-05-14T03:33:42.687 回答