Add a ContainerView inside a UIViewController created from .xib

放肆的年华 提交于 2019-11-30 00:23:49

问题


I have a .xib file and i want to add it a container view (to place inside a ViewController). Unfortunately a container view is only disposable by storyboard. But when i create a .xib file and i search for the container view controller, i don´t found it. Can someone give me a tips how to achieve my task?


回答1:


If you're using a xib instead of a storyboard, you can just add a plain UIView to the xib to act as a container. Then in code, add your childViewController's view as a subview of the container. Here, I've followed the appropriate child view controller methods and added layout constraints to ensure its frame updates with the container's frame:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIViewController *childViewController = ...; // create your child view controller

    [self addChildViewController:childViewController];
    [self.containerView addSubview:childViewController.view];
    [childViewController didMoveToParentViewController:self];

    NSArray *horzConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[childView]|"
                                                                   options:0
                                                                   metrics:nil
                                                                     views:@{@"childView" : childViewController.view}];

    NSArray *vertConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[childView]|"
                                                                   options:0
                                                                   metrics:nil
                                                                     views:@{@"childView" : childViewController.view}];

    [self.view addConstraints:horzConstraints];
    [self.view addConstraints:vertConstraints];

    childViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
}



回答2:


Check this:

SelectDateViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"selectDateVCID"];
[self addChildViewController:vc];
[vc.view setFrame:CGRectMake(0.0f, 0.0f, self.selectDateContainerView.frame.size.width, self.selectDateContainerView.frame.size.height)];
[self.selectDateContainerView addSubview:vc.view];
[vc didMoveToParentViewController:self];


来源:https://stackoverflow.com/questions/32549731/add-a-containerview-inside-a-uiviewcontroller-created-from-xib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!