设置自动布局约束后,子视图没有宽度或高度

时间:2013-09-05 08:19:01

标签: ios autolayout

我正在尝试在其父视图中布局子视图控制器的视图。子视图控制器的视图(子视图)必须跨越整个父视图,但14像素的上边距除外。

在我看来,下面的代码应该足以实现这一点,但是当子视图的原点变得正确(0,14)时,它的宽度和高度都是0。

我正在使用以下代码添加子视图控制器并设置其视图约束:

[self.view addSubview:_infoController.view];
[self addChildViewController:_infoController];
[_infoController didMoveToParentViewController:self];

UIView *infoView = _infoController.view;
NSDictionary *viewsDict = NSDictionaryOfVariableBindings(infoView);
NSArray *heightConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-14-[infoView]|" options:0 metrics:nil views:viewsDict];
NSArray *widthConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[infoView]|" options:0 metrics:nil views:viewsDict];

NSMutableArray *constraints = [NSMutableArray array];
[constraints addObject:[heightConstraints objectAtIndex:0]];
[constraints addObject:[widthConstraints objectAtIndex:0]];

[infoView setTranslatesAutoresizingMaskIntoConstraints:NO];

[self.view addConstraints:constraints];
[self.view setNeedsUpdateConstraints];

这会产生一个带有原点(0,14)和大小(0,0)的视图。

或者,当我不禁用'translatesAutoresizingMaskIntoConstraints'属性时,视图确实具有有效的原点和大小,但是存在约束冲突并且丢弃了14px的上边距。显示的冲突如下:

"<NSLayoutConstraint:0xba6bad0 V:|-(14)-[UIView:0xba6aec0]   (Names: '|':UIView:0xa3b9200 )>",
"<NSAutoresizingMaskLayoutConstraint:0xb8b4db0 h=--& v=--& V:[UIView:0xba6aec0(480)]>",
"<NSAutoresizingMaskLayoutConstraint:0xb8b4180 h=--& v=--& UIView:0xba6aec0.midY == + 240>"


Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0xba6bad0 V:|-(14)-[UIView:0xba6aec0]   (Names: '|':UIView:0xa3b9200 )>

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

出于某种原因,

constraintsWithVisualFormat:options:metrics:views:会返回NSArray。原因是视觉格式通常定义了多个约束。

但是除了每个视觉格式的第一个之外,你正在抛弃所有约束。您只需将每种可视格式的第一个约束添加到视图中。很可能您没有指定足够的约束来定义完整的布局。

您的代码应如下所示

NSArray *heightConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-14-[infoView]|" options:0 metrics:nil views:viewsDict];
[self.view addConstraints:heightConstraints];
NSArray *widthConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[infoView]|" options:0 metrics:nil views:viewsDict];
[self.view addConstraints:widthConstraints];

您不需要constraints数组。

答案 1 :(得分:2)

请改为尝试:

[self.view addSubview:_infoController.view];
[self addChildViewController:_infoController];
[_infoController didMoveToParentViewController:self];

UIView *infoView = _infoController.view;
NSDictionary *viewsDict = NSDictionaryOfVariableBindings(infoView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-14-[infoView]|" options:0 metrics:nil views:viewsDict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[infoView]|" options:0 metrics:nil views:viewsDict]];

[infoView setTranslatesAutoresizingMaskIntoConstraints:NO];