我有一个.xib文件,我想添加一个容器视图(放在ViewController中)。不幸的是,容器视图只能通过故事板一次性使用。但是当我创建一个.xib文件并且我搜索容器视图控制器时,我没有找到它。有人可以给我一些如何实现我的任务的提示吗?
答案 0 :(得分:27)
如果您使用的是xib
而不是storyboard
,则只需将UIView
添加到xib
即可充当容器。然后在代码中,添加childViewController' s view
作为容器的子视图。在这里,我遵循了相应的子视图控制器方法并添加了布局约束,以确保其框架更新与容器的框架:
- (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;
}
答案 1 :(得分:0)
检查一下:
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];