In Visual Formatting Language is there a way to keep two elements in the same position on one axis?
For example I have a UILabel
and a UITextField
that I want alongside each other horizontally. When laying out the vertical constraints is there anyway of specifying this?
Something like this would be ideal:
|-40-([label][field])-10-[otherStuff]
...where [label]
and [field]
both have the same Y position, but are 40 points down from the top of the superview and 10 points beneath them is [otherStuff]
.
Is this possible?
Or should I nest the [label]
and [field]
in their own UIView and then lay that out?
The visual format language does not support this in and of itself. First, the horizontal layout and the vertical layout have to be done in two separate strings. However +[NSLayoutConstraint constraintsWithVisualFormat:options:metrics:views:]
takes options which can include alignment.
So, you could use:
NSDictionary* views = NSDictionaryOfVariableBindings(field, label);
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-40-[label]-10-[otherStuff]" options:0 metrics:nil views:views];
[field.superview addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[label][field]" options:NSLayoutFormatAlignAllBaseline metrics:nil views:views];
[field.superview addConstraints:constraints];
In the second case, the NSLayoutFormatAlignAllBaseline
makes it so that, not only does field
trail label
, but they are in the same vertical position (based on their baseline, which is probably better than aligning their center, top, or bottom).