Visual Format Language

Episode #134 | 13 minutes | published on August 28, 2014
Subscribers Only
In this episode we explore Apple's Visual Format Language for building Auto Layout Constraints. While a bit strange at first glance, the Visual Format Language can really convey a lot of layout information in just a few characters in comparison to the manual building of NSLayoutConstraints can be.

Episode Links

Converting the Headline View to VFL

    [self.view addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"|-[headlineView]-|"
                                             options:0
                                             metrics:nil
                                               views:NSDictionaryOfVariableBindings(headlineView)]
     ];

This specifies the horizontal layout for the headline view.

Specifying the Vertical Layout

    NSDictionary *metrics = @{
                              @"topPadding": @60,
                              @"headlineViewHeight": @100
                              };
    [self.view addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(topPadding)-[headlineView(headlineViewHeight)]-[leftView]-|"
                                             options:NSLayoutFormatAlignAllLeft
                                             metrics:metrics
                                               views:NSDictionaryOfVariableBindings(headlineView, leftView)]
     ];

Note that we can't specify the percentage width for the leftView, so we have to do this in the more verbose NSLayoutConstraint call like last episode.

Laying Out the Button

The button is only related to the leftView, so we can avoid the | anchors, since they are already specified.

    [self.view addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"[leftView]-[button]"
                                             options:NSLayoutFormatAlignAllCenterY
                                             metrics:nil
                                               views:NSDictionaryOfVariableBindings(leftView, button)]
     ];

Note that here we can also specify the y value due to the options passed in.

blog comments powered by Disqus