Skip to content

Variable Bindings

Published:
2 min read

Here is a little but very useful snippet:

NSDictionary *views = NSDictionaryOfVariableBindings(redView, blueView);## What?!Working with auto layout in code may be painful. Especially if you’re trying to setup the constraints for more than a few views.

Here is an example that creates auto layout constraints, using visual format language, for two views to have a fixed vertical spaces both between each other and super view:

NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat: @“V:|-[redView(==blueView)]-0-[blueView]-|” options:0 metrics:nil views:@{@“redView”: redView, @“blueView”: blueView}];

[self.view addConstraints:constraints];In this one liner(!), we need to provide our views in a dictionary with the keys being the same as the visual format and the values being our views.

This is very open for typos. And if that’s the case, you may need some time to spend on debugging.

But in a relatively shorter wayInstead if we use variable bindings, it will create the same dictionary for us, using the variable names as keys and variables themselves as values. Also it’s easy on the eye too!

NSDictionaryOfVariableBindings(redView, blueView)So you can have a full setup like:

NSDictionary *views = NSDictionaryOfVariableBindings(redView, blueView);

NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat: @“V:|-[redView(==blueView)]-0-[blueView]-|” options:0 metrics:nil views:views]; [self.view addConstraints:constraints];

constraints = [NSLayoutConstraint constraintsWithVisualFormat: @“H:|-[redView]-|” options:0 metrics:nil views:views]; [self.view addConstraints:constraints];

constraints = [NSLayoutConstraint constraintsWithVisualFormat: @“H:|-[blueView]-|” options:0 metrics:nil views:views]; [self.view addConstraints:constraints];Let me know if that made your day! :)

New posts, shipping stories, and nerdy links straight to your inbox.

2× per month, pure signal, zero fluff.


Edit on GitHub
Share this post on: