Is it possible to equally distribute left and right space for b
in @"|-[a(5)]-[b(8)]-[c(5)]-|"
using visual format strings?
This appendix shows how to use the Auto Layout Visual Format Language to specify common constraints, including standard spacing and dimensions, vertical layout, and constraints with different priorities. In addition, this appendix contains a complete language grammar.
Select the controls where you want to adjust spacing. From the Format menu, choose Horizontal Spacing or Vertical Spacing. From the cascading menu, choose one of the following: Make Equal, to make all horizontal and vertical spaces between controls the same size.
Make Equal, to make all horizontal and vertical spaces between controls the same size. The amount of horizontal and vertical space will vary depending on the area available for displaying controls and the combined width of all controls.
Auto Layout prints constraints to the console using the visual format language; for this reason, the debugging messages look very similar to the code used to create the constraints. The visual format language lets you create multiple constraints at once, using a very compact expression.
Apple's Auto Layout Guide suggests using "spacer views". Here's the solution for laying out your three views with equal spacing horizontally:
// create views dictionary
NSMutableDictionary *viewsDictionary = [NSMutableDictionary dictionary];
[viewsDictionary addEntriesFromDictionary:NSDictionaryOfVariableBindings(viewA, viewB, viewC)];
// create 4 spacer views
for (int i = 0; i < 4; i++) {
UIView *spacerView = [[UIView alloc] init];
spacerView.hidden = YES;
[self addSubview:spacerView];
[viewsDictionary setObject:spacerView
forKey:[NSString stringWithFormat:@"spacer%d", i + 1]];
}
// disable translatesAutoresizingMaskIntoConstraints in views for auto layout
[viewsDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
{
[obj setTranslatesAutoresizingMaskIntoConstraints:NO];
}];
// add constraints
[superview addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:
@"|[spacer1(>=0)][viewA][spacer2(==spacer1)][viewB][spacer3(==spacer1)][viewC][spacer4(==spacer1)]|"
options:kNilOptions
metrics:nil
views:viewsDictionary]];
Note that spacer1
's width is set to be more than 0. Subsequent spacer views are set to have equal widths with spacer1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With