AutoLayout和ChildViewControllers的问题(ChildVCs视图的大小不正确)

dji*_*oul 5 ios autolayout childviewcontroller

我在做一件相当简单的事情时遇到了一些困难,我错过了一些但却看不到......

我用一个非常简单的应用程序(使用IB)重现了这个问题:

  • App的主ViewController是一个UINavigationController.
  • NavigationController的根目录是"FirstViewController".
  • FirstViewController和SecondViewController是空的UIViewController子类.
    • 他们的XIB文件在创建类时由XCode生成,启用了AutoLayout.
    • 我将标签放在SecondViewController的顶部和底部(垂直空间约束= 0).

使用ChildViewControllers

问题是如果我通过"ChildViewControllers"方法显示SecondViewController,它在我的iPhone4上出错:我没有看到底部标签.

// In FirstViewController.m
- (IBAction)child:(id)sender {
    [self addChildViewController:self.secondVC];
    [self.view addSubview:self.secondVC.view];
    [self.secondVC didMoveToParentViewController:self];
}
Run Code Online (Sandbox Code Playgroud)

使用NavigationController

如果我通过NavigationController显示"SecondViewController",一切都很好,SecondViewController正确显示.

// In FirstViewController.m
- (IBAction)push:(id)sender {
    [self.navigationController pushViewController:self.secondVC animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

此外,只要SecondViewController通过NavigationController显示一次,它就会始终显示良好.

我肯定错过了什么,但是什么?:p你有什么想法吗?

我在dropbox上载了简单项目:https://dl.dropbox.com/u/36803737/sharebox/AutoLayoutTest.zip

谢谢!

朱利安

rde*_*mar 27

您的Dropbox链接不起作用,所以我无法尝试这一点.在将其添加为子视图之前,请尝试设置secondVC的框架:

secondVC.view.frame = self.view.bounds;
Run Code Online (Sandbox Code Playgroud)

如果你想用约束来做,我这样做:

- (IBAction)child:(id)sender {
    [self addChildViewController:self.secondVC];
    [self.view addSubview:self.secondVC.view];
    [self constrainViewEqual:secondVC.view];
    [self.secondVC didMoveToParentViewController:self];
}

-(void)constrainViewEqual:(UIView *) view {
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSLayoutConstraint *con1 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    NSLayoutConstraint *con3 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeWidth relatedBy:0 toItem:view attribute:NSLayoutAttributeWidth multiplier:1 constant:0];
    NSLayoutConstraint *con4 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:0 toItem:view attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
    NSArray *constraints = @[con1,con2,con3,con4];
    [self.view addConstraints:constraints];
}
Run Code Online (Sandbox Code Playgroud)

由于我经常使用约束,因此我在UIView的类别中使用上述方法(和其他方法)来保持我的代码看起来更清晰.