Can't programmatically set NSConstraints on view
-
21-12-2019 - |
Question
I'm trying to do something very simple: Creating a view from scratch, adding it to the controller's view, and have it stretch edge to edge to its superview, but I get console warning once the app runs, saying the constraints cannot be simultaneously added to the view.
backView = [UIView new];
backView.backgroundColor = [UIColor redColor];
[[self view] insertSubview:backView aboveSubview:tableview];
[[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[back]-0-|"
options:0
metrics:nil
views:@{@"back": backView}]];
[[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[back]-0-|"
options:0
metrics:nil
views:@{@"back": backView}]];
Solution
When you create a UIView
in code it translates auto-resizing mask to constraints
.
i.e. it takes the frame you gave it when you created it and the auto-resizing mask and converts them into NSLayoutConstraints
.
These auto-generated constraints are then conflicting with the constraints that you are adding manually.
If I'm right then you will be able to fix it by adding the line...
backView.translatesAutoresizingMaskIntoConstraints = NO;
right after the first line and it should fix the problem.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow