24

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?

Fahem Issameddine
  • 293
  • 1
  • 2
  • 10

2 Answers2

33

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;
}
jungledev
  • 4,195
  • 1
  • 37
  • 52
johnpatrickmorgan
  • 2,372
  • 2
  • 13
  • 17
  • 1
    Getting error *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse constraint format: Unable to interpret '|' character, because the related view doesn't have a superview H:|[childView]| ^' – Abhishek Thapliyal Jan 24 '17 at 11:17
  • 1
    @AbhishekThapliyal it is added to a superview in the line `[self.containerView addSubview:childViewController.view];`. Probably your `containerView` is nil. Check your IBOutlet. – johnpatrickmorgan Jan 24 '17 at 15:07
3

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];
reza_khalafi
  • 6,230
  • 7
  • 56
  • 82