I always create my views in code and so have never used auto layout (until now). The reason behind not using nibs is because I like the code better and it's simpler to maintain via GitHub etc, but enough about that.
I have a situation where I have three labels on the screen placed next to each other. Like so: |Label1| - some space - |Label2| - some space - |Label3|
. Some space is let's say 15pts. Now what I would like to accomplish is that when I change the text of the labels I will call sizeToFit
on them and would like that they would remain 10pts apart from each other. I know I could to this with a bit of math which is not even hard but I think that auto layout will be easier and more understandable and I will learn something new along the way. So what I did is:
- Alloc & init all the labels
- Give each label a frame (and set font, text color, etc)
- Add the labels as a subview
Then I tried to set up the constraints between them like so:
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[label1]-15-[label2]-15-[label3]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(label1, label2, label3)];
[self addConstraints:constraints]; //Im subclassing an UIView that's why self
But I get an error saying:
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)
(
"<NSLayoutConstraint:0x14c14110 H:[UILabel:0x14c12ab0]-(15)-[UILabel:0x14c12f80]>",
"<NSAutoresizingMaskLayoutConstraint:0x14c08b00 h=--& v=--& UILabel:0x14c12ab0.midX == + 195>",
"<NSAutoresizingMaskLayoutConstraint:0x14c0dd90 h=--& v=--& H:[UILabel:0x14c12ab0(40)]>",
"<NSAutoresizingMaskLayoutConstraint:0x14c1c170 h=--& v=--& UILabel:0x14c12f80.midX == + 237.5>",
"<NSAutoresizingMaskLayoutConstraint:0x14c12f00 h=--& v=--& H:[UILabel:0x14c12f80(40)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x14c14110 H:[UILabel:0x14c12ab0]-(15)-[UILabel:0x14c12f80]>
Even if I try to do this just on the label 2 and 3 the same thing happens. I do not fully understand what the NSLog is saying.
Any help would be much appreciated. Also if you have any good links on where to "decode" those h=--& v=--& UILabel:0x14c12f80.midX == + 237.5
things would be awesome.