在从.xib创建的UIViewController中添加ContainerView

Fah*_*ine 23 objective-c xib uicontainerview

我有一个.xib文件,我想添加一个容器视图(放在ViewController中).不幸的是,容器视图只能通过故事板一次性使用.但是当我创建一个.xib文件并且我搜索容器视图控制器时,我没有找到它.有人可以给我一些如何实现我的任务的提示吗?

joh*_*gan 31

如果您使用的是xib代替的storyboard,你可以再补充一个普通UIViewxib作为容器.然后在代码中,将childViewController添加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;
}
Run Code Online (Sandbox Code Playgroud)