以编程方式添加控制器视图时,自定义自动布局约束会中断

Dri*_*ico 3 ios autolayout nslayoutconstraint

我有一个myController,我在代码中插入(在self =一个根视图控制器中)这样:

    MyViewController* myController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
    [self addChildViewController:myController];
    [self.view addSubview:myController.view];
    myController.view.frame = CGRectMake(0, 504, 320, 216);
Run Code Online (Sandbox Code Playgroud)

在MyViewController的xib文件中,我只有2个视图,一个在另一个上面.让我们说顶视图称为View1,底部视图称为View2.View0是主视图.

我添加了以下垂直NSLayoutConstraints:V:[View2(40)] V:| - (0)-View1(名称:'|':View0)V:View2-(0) - | (名称:'|':View0)V:View1-(0)-View2

也就是说,View1在顶部触摸View0,在底部触摸View2.View2在顶部触摸View1,在底部触摸View0,并且具有40的恒定高度.

当我以肖像方式运行时,每件事情似乎都可以.但是当我转向横向时,我有时会出现以下错误.

Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
"<NSAutoresizingMaskLayoutConstraint:0xd17cc00 h=--& v=--& V:[UIView:0xd174a30(268)]>",
"<NSLayoutConstraint:0x9469890 V:[View2(40)]>",
"<NSLayoutConstraint:0x9468e90 V:|-(0)-View1   (Names: '|':View0 )>",
"<NSLayoutConstraint:0x9468ef0 V:View2-(0)-|   (Names: '|':View0 )>",
"<NSLayoutConstraint:0x94676f0 V:View1-(0)-View2>",
"<NSAutoresizingMaskLayoutConstraint:0x9450640 h=-&- v=-&- UIView:0000.height == UIView:0xd174a30.height - 268>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x9469890 V:[View2(40)]>

Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
Run Code Online (Sandbox Code Playgroud)

有人知道我为什么这么做吗?我应该做些什么来保持我定义的约束为先?

Dri*_*ico 7

好的,最后,为了解决这个问题,我不得不在View0上将translatesAutoresizingMaskIntoConstraints设置为NO.

然后,为了很好地显示我的View0,我必须为View0手动创建NSLayoutConstraint并将这些约束添加到View0的superview.