简体   繁体   English

带情节提要的IBAction子视图

[英]IBAction Subview with Storyboard

I'm trying to add a subview using storyboard. 我正在尝试使用情节提要添加子视图。 It's being displayed correctly, but there's no button ( IBAction ) in subview that works correctly, even with empty code, the app always crashes when clicked. 它已正确显示,但是子视图中没有任何按钮( IBAction )可以正常工作,即使使用空代码,单击该应用程序也始终会崩溃。

TableViewController.m TableViewController.m

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

SubviewViewController.m SubviewViewController.m

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

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: 正确的方法是将控制器添加为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). 您可能还需要设置子视图的框架(subview.view.frame = self.view.bounds,如果您希望它的大小相同)。

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. 或者,您可以在xib文件中创建视图而不是视图控制器,并将其添加为视图的子视图。 In that case, you would set the file's owner of the xib to TableViewController, and put the button's method in TableViewController. 在这种情况下,您可以将文件的xib所有者设置为TableViewController,并将该按钮的方法放在TableViewController中。

Look into UIContainerView, it handles sub-view controllers. 查看UIContainerView,它处理子视图控制器。 You will need to handle your own communication between parent and child view controllers, but other than that it will work like you need it to for a sub-view, as long as your sub-view has the proper outlets and actions set up in the storyboard with it's view controller. 您将需要在父视图控制器和子视图控制器之间处理您自己的通信,但除此之外,只要您的子视图具有在其中设置的正确插座和操作,它将像您需要它一样用于子视图。故事板及其视图控制器。

Have a look for more in-depth information on container views. 查看有关容器视图的更多深入信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM