The Egger Apps Blog

31 Jan 2014

Cocoa: Creating Autolayout Constraints in Code

Autolayout is one of the best new features recently introduced in Cocoa. However, setting up layout constraints in Interface Builder can be an infuriating experience. Fortunately, Apple also introduced something they call the "Visual Format Language" (VFL) for creating autolayout constraints in code. The VFL allows you to describe layout constraints using a syntax similar to ASCII-Art. For example, if you'd like to lay out three buttons next to another, stuck to the right edge a dialog, you could express this like this:


Sounds concise and straightforward, right? Well, that's until you actually write down the code to install these constraints:

NSButton *donSaveButton, *cancelButton, *OKButton, *superview; // assume these exist
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat: @"[dontSaveButton]-[cancelButton]-[OKButton]-|"
                                                               options: 0 
                                                               metrics: nil
                                                                 views: NSDictionaryOfVariableBindings(donSaveButton, cancelButton, OKButton)];
[superview addConstraints: constraints];

Now that is quite a mouthful! And that's assuming you don't keep any view references in a dictionary or an array, because then you'd need additional assignments. Wouldn't it be nice if there was a more concise way of specifying constraints?

Something more like this:

NSButton *donSaveButton, *cancelButton, *OKButton, *superview; // assume these exist
[superview addConstraintsWithFormat: @"[%v]-[%v]-[%v]-|", donSaveButton, cancelButton, OKButton];

Well, I implemented exactly that in a convenient category for NSView. I named it ConciseConstraints, and you can find it on Github.