我有一个 .xib 文件,我想给它添加一个容器 View (放置在 ViewController 中)。不幸的是,容器 View 只能由 Storyboard 一次性使用。但是当我创建一个 .xib 文件并搜索容器 View Controller 时,我没有找到它。有人可以给我提示如何完成我的任务吗?
最佳答案
如果您使用的是 xib
而不是 storyboard
,您只需将普通的 UIView
添加到 xib
充当容器。然后在代码中,将您的 childViewController 的 view
添加为容器的 subview 。在这里,我遵循了适当的 subview Controller 方法并添加了布局约束以确保其框架与容器的框架一起更新:
- (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;
}
关于objective-c - 在从 .xib 创建的 UIViewController 中添加一个 ContainerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32549731/