Question

When adding a view programatically, is there a more concise way of fitting it to the parent view than the below?

NSDictionary *views = @{ @"view" : view };
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|" options:0 metrics:nil views:views];
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[view]-0-|" options:0 metrics:nil views:views];
[parentView addConstraints:horizontalConstraints];
[parentView addConstraints:verticalConstraints];
Was it helpful?

Solution

Without using any extra dependencies the most concise version of your code is this:

NSDictionary *views = @{ @"view" : view };
[parentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[view]|" options:0 metrics:nil views:views]];
[parentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:views]];

(You don't need to have the array variables, zero padding assumed and H: is the default axis value).

You could use my auto layout convenience category which would allow the following:

[view pinToSuperviewEdges:JRTViewPinAllEdges inset:0];

OTHER TIPS

From your code, you code improve slightly, though no more correct by using NSDictionaryOfVariableBindings() to creat your views dictionary. If you want zero spaced constraints between a view edge and the corresponding superview edge, you can omit the dashes and zeros from the VFL strings.

Beyond that you would need to use a DSL which means something else to learn and still understand and debug in terms of the true form.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top