HVFL is a language designed to constrain UI elements in a simple and quick fashion. Generally, VFL has an advantage over traditional UI customization in the Interface Builder because it's much more readable, accessible and compact.
Here's an example of VFL, in which three UIViews are constrained from left to right, filling up superView.width
, with aGradeView
"H:|[bgView][aGradeView(40)][bGradeView(40)]|"
There are two axes in which we can constrain UI Objects to, Horizontally and Vertically.
Each line of VFL always begins with H:
or V:
.
If neither are present, the default option is H:
Moving on, we have a pipeline. |
This symbol, or the pipe, refers to the superview.
If you take a closer look at the snippet of VFL code above, you'd notice two of these pipelines.
This signifies the two horizontal ends of the superview, the outerleft and outerright boundaries.
Next up you'll see some square brackets, within the first set of square brackets, we have bgView
. When we've got square brackets, it's referring to a UI element, now you might wonder how we establish a link between the name and the actual UI element, an outlet perhaps?
I'll cover that at the end of the post.
If you take a look at the second pair of square brackets [aGradeView(50)]
, we have some parentheses encapsulated within as well, when that is present, it defines the width/height depending on the axes, which in this case is 50 pixels in width.
The first square brackets [bgView]
did not have a width explicitly defined, meaning that it'll span out as far as possible.
Alright, that's it for the basics, more on the advanced stuff in another example.
// 1. create views UIView *blueView = [[UIView alloc] init]; blueView.backgroundColor = [UIColor blueColor]; [self.view addSubview:blueView]; UIView *redView = [[UIView alloc] init]; redView.backgroundColor = [UIColor redColor]; [self.view addSubview:redView]; // 2. forbid Autoresizing blueView.translatesAutoresizingMaskIntoConstraints = NO; redView.translatesAutoresizingMaskIntoConstraints = NO; // 3. make contraints // horizontal NSArray *blueH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[blueView]-20-|" options:NSLayoutFormatAlignAllLeft metrics:nil views:@{@"blueView" : blueView}]; [self.view addConstraints:blueH]; // vertical NSArray *blueVandRedV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[blueView(50)]-20-[redView(==blueView)]" options:NSLayoutFormatAlignAllTrailing metrics:nil views:@{@"blueView" : blueView, @"redView" : redView}]; [self.view addConstraints:blueVandRedV]; NSLayoutConstraint *redW = [NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0]; [self.view addConstraint:redW];