顶部和顶部的Autolayout问题底部布局指南

时间:2014-04-11 07:29:55

标签: ios autolayout nslayoutconstraint

我有一些问题要以编程方式从我的视图和controller.topLayoutGuide&中设置NSLayoutconstraints。 controller.bottomLayoutGuide。

在viewDidLoad中使用此代码:

_mainView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:_mainView];
[self.view removeConstraints:self.view.constraints];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_mainView]-0-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:NSDictionaryOfVariableBindings(_mainView)]];
id top = self.topLayoutGuide;
id bottom = self.bottomLayoutGuide;
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[top]-0-[_mainView]-0-[bottom]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(top, _mainView, bottom)]];
[self.view layoutSubviews];

结果是:

http://i61.tinypic.com/2h34shh.png

(_ mainView有深灰色背景色)

如果我设置相对于超视图的约束,它可以工作:

_mainView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:_mainView];
[self.view removeConstraints:self.view.constraints];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_mainView]-0-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:NSDictionaryOfVariableBindings(_mainView)]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_mainView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_mainView)]];
[self.view layoutSubviews];

http://i62.tinypic.com/24ouiop.png

我的错误在哪里? 视图控制器层次结构是uitabbarcontroller - > uinavigationController - > myViewController


解决!

错误是:

[self.view removeConstraints:self.view.constraints];

我用

更改了代码
for(NSLayoutConstraint *c in self.view.constraints)
    if(c.firstItem == _mainView || c.secondItem == _mainView)
       [self.view removeConstraint:c];

它有效。 不管怎么说,还是要谢谢你! ;)

1 个答案:

答案 0 :(得分:1)

检查self.topLayoutGuide和self.bottomLayoutGuide是否为零。您可能忘记在Interface Builder中设置插座。