I am learning how to programmatically use NSLayoutConstraints
and mainly constraintsWithVisualFormat
, and to do so I am trying to recreate a view with this layout:
This view is composed of three subviews, a 35x35px circle icon that's 15px away from the left of the view, a checkmark icon 15px away from the right of the view, and a label in the middle, 9px away from the circle icon and the checkmark.
I tried this :
[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-15-[icon(==35)]-9-[label]-9-[checkmark(==24)]-15-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(icon, label, checkmark)]];
The icon is at the right location and the label starts where it should too, but I can't place the checkmark where I want... it actually starts 9px right of the label, and in the second situation (with a long label), the checkmark is outside of the view.
What am I doing wrong? Thanks for your help.
Analyse your constraint, you already have ambiguity in your constraint.
H:|-15-[icon(==35)]-9-[label]-9-[checkmark(==24)]-15-|
Checkmark is 15 pixels away from right margin but then it is also 9 pixels right to label. What if icon, label occupy only 20% of the total width, in that case your check mark will occupy rest of the space from label to 15 pixels away from right margin. That will make checkmark grow. UIImageView can use intrinsic contentSize if the constraint are right. The way you fix this is having inequality constraint like this,
H:|-15-[icon(==35)]-9-[label]-(>=9)-[checkmark(==24)]-15-|
This now mean that checkmark is always 15 pixels from right but then the space between label and checkmark is greater than 9 pixels. So, checkmark would always be fixed at 15 pixels from right but the space between label and checkmark can vary.