When I add a UIContainerView to a view controller

2020-04-18 08:04发布

问题:

When I add a UIContainerView to a view controller it's type is UIView.

How do I get to the UIViewController for the embedded view?

I need to set some properties of the embedded view view controller.

Thank you

回答1:

In prepareForSegue:sender: in the containing view controller, you access the embedded view controller as segue.destinationViewController. If you have multiple segues out of the containing view controller, you'll want to give each one a unique identifier string in the storyboard, so you can check segue.identifier in prepareForSegue:sender: to see which segue you're dealing with.

You can save segue.destinationViewController in an instance variable if you need to send it more messages later, after prepareForSegue:sender: has returned.



回答2:

If you are using storyboard, you can access the child view controller in the prepareForSegue method, the segue is from the container view to its child view controller, if you're using code to add child view controller, you can access it directly



回答3:

In UIContainerView, you use Storyboard directly Embed to UIViewController, or you use coding way access childViewController, First, i have the storyboard solution is given below,

i am create parentViewController add UIContainerView then drag to ChildViewController show option to select the Embed finally run your project

Then Another Way to Embed the ChildViewController from ParentViewController using Coding format is given below

@property (weak, nonatomic) UIViewController *currentViewController;
@property (weak, nonatomic) IBOutlet UIView *containerView;

ViewDidLoad method:

_currentViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"childViewController"];
    _currentViewController.view.layer.cornerRadius = 8.0f;
    _currentViewController.view.translatesAutoresizingMaskIntoConstraints = NO;

    [self addChildViewController:_currentViewController];
    [self addSubview:_currentViewController.view toView:_containerView];



- (void)addSubview:(UIView *)subView toView:(UIView*)parentView {
    [parentView addSubview:subView];

    NSDictionary * views = @{@"subView" : subView,};
    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[subView]|"
                                                                   options:0
                                                                   metrics:0
                                                                     views:views];
    [parentView addConstraints:constraints];
    constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[subView]|"
                                                          options:0
                                                          metrics:0
                                                            views:views];
    [parentView addConstraints:constraints];
}

hope its helpful..



标签: ios uiview