p.ferraris
p.ferraris

Reputation: 21

Autolayout issue with top & bottom layout guide

I have some problem to set NSLayoutconstraints programmatically from my view and controller.topLayoutGuide & controller.bottomLayoutGuide.

with this code in 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];

the result is that:

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

(_mainView has dark gray background color)

if i set up the constraints relative to the superview it works:

_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

where is my error? the view controller hierarchy is uitabbarcontroller -> uinavigationController -> myViewController


SOLVED!

the error was:

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

I changed the code with

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

and it worked. thanks anyway! ;)

Upvotes: 1

Views: 2283

Answers (1)

Z S
Z S

Reputation: 7481

Check if self.topLayoutGuide and self.bottomLayoutGuide is not nil. You might have forgotten to set the outlet in Interface Builder.

Upvotes: 1

Related Questions