Reputation: 2600
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.
TableViewController.m
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Load SubView
SubviewViewController *subview = [self.storyboard instantiateViewControllerWithIdentifier:@"SubviewViewController"];
[self.view addSubview:subview.view];
}
...
SubviewViewController.m
- (IBAction)btnCloseSubview:(id)sender
{
// Crashes the app when clicked, even empty as it's.
}
Upvotes: 2
Views: 926
Reputation: 4285
Look into UIContainerView, it handles sub-view controllers. 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.
Upvotes: 2
Reputation: 104082
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.
Upvotes: 5