Using the VFL in Auto layout (Visual format language)-code for automatic layout

Source: Internet
Author: User


This article will show you how to use the VFL to implement automatic layout with a simple UI. The automatic layout avoids the use of code to optimize and to implement different UIs based on content.

One: API Introduction

    1. Nslayoutconstraint API

1234 NSLayoutConstraint+ (NSArray *)constraintsWithVisualFormat:(NSString *)format options:(NSLayoutFormatOptions)optsmetrics:(NSDictionary *)metricsviews:(NSDictionary *)views;

Parameter description:

Format: This parameter is your VFL statement, for example: @ "h:|-[button]-|"

OPTs: Enumeration parameters, default write 0, specific to your implementation of the requirements to choose the enumeration you want

Metrics: Here is a dictionary, when using dynamic Data in format such as the above sentence: @ "H:|-[button (==width)]-|", indicating that the width of the button is wide, then where to find this parameter? is to find the value of key pair in this dictionary, if you do not find this value, the app will be crash.

Views: As the name implies, this is all you use in the VFL view, that in the above example should be how to preach it? The result is this: nsdictionaryofvariablebindings (button). If you use multiple view, you can nsdictionaryofvariablebindings (button,button1 , Button3 ...), this name also corresponds to one by one of the parameter format, which is indispensable.

2.UIView API

12 UIView- (void)addConstraints:(NSArray *)constraints;

In the above 1 the return value type is Nsarray, and now the parameter of this method is exactly a nsarray type. Then direct the return value of the previous method as a parameter to this method. If you have more than one VFL, you can also use a mutable array (Nsmutablearray) to put together the data returned by the VFL, and then call the Addconstraints: method.

Second: Simple to use

1. Use of single controls (not associated with other controls, such as voids, etc.)

Create a new single-page project, application, and add the following code to the project

12345678910111213141516171819202122232425262728293031 #import "ViewController.h"@interface ViewController () @end @implementation ViewController - (void)viewDidLoad {    [superviewDidLoad];    UIButton *button=[[UIButton alloc]init];    [button setTitle:@"点击一下"forState:UIControlStateNormal];    button.translatesAutoresizingMaskIntoConstraints=NO;    [button setBackgroundColor:[UIColor blackColor]];    [self.view addSubview:button];    NSArray *constraints1=[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[button]-|"                            options:0                            metrics:nil                            views:NSDictionaryOfVariableBindings(button)];         NSArray *constraints2=[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[button(==30)]"                            options:0                            metrics:nil                            views:NSDictionaryOfVariableBindings(button)];         [self.view addConstraints:constraints1];    [self.view addConstraints:constraints2];         } @end

Run the program as follows:

As you can see, our new button has come out to prove that the above automatic layout statement (VFL) is already in effect. So let's take a closer look at what these statements mean.

1234 NSArray *constraints1=[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[button]-|"                         options:0                         metrics:nil                         views:NSDictionaryOfVariableBindings(button)];

Here means: button in the horizontal direction distance its superview, around each 20px, for example, here his size is 320-20*2=280. @ "h:|-[button]-|" In this statement, where "H:" is the constraint that indicates that this is a horizontal direction, the "|" Is the Superview, "-" represents an interval space, if this interval is like superview between, then is 20px, if it is two of the same level of view, such as @ "[Button]-[button1]", then this represents 8px.

1234 NSArray *constraints2=[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[button(==30)]"                         options:0                         metrics:nil                         views:NSDictionaryOfVariableBindings(button)];

A bit different from the above, @ "V:|-20-[button (==30)]", where "V:" means that this is the vertical direction of the constraint, "|-20-" here means that the distance from the head is 20px, equivalent to the Y coordinate of 20. The following "[Button (==30)]", is to specify that the height of the button 30px.y coordinates fixed, the height is fixed, then the view constraint is complete. If you have a need, your height value (or any other type) can be expressed using >=,==,<=, even if you can combine it with, like the above 30, you can specify a difference, such as: (>=30,<=40), which is also possible. If you want to express his priority, you can use @ "V:|-20-[button ([email protected])]", this @1000 is his level. You can adapt Xib or SB to do more processing of its priority.

PS: It is worth noting that in the UIView created with the code, be sure to add the following code

1 button.translatesAutoresizingMaskIntoConstraints=NO;

If you do not have the above line, your constraint will not take effect, and the console will output a series of errors.

2: Association between multiple controls using

Based on the above code, we re-added a piece of code, now all the code is as follows:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 #import "ViewController.h"@interface ViewController () @end @implementation ViewController  - (void)viewDidLoad {    [superviewDidLoad];    UIButton *button=[[UIButton alloc]init];    [button setTitle:@"点击一下"forState:UIControlStateNormal];    button.translatesAutoresizingMaskIntoConstraints=NO;    [button setBackgroundColor:[UIColor blackColor]];    [self.view addSubview:button];    NSArray *constraints1=[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[button]-|"                           options:0                           metrics:nil                            views:NSDictionaryOfVariableBindings(button)];         NSArray *constraints2=[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[button(==30)]"                            options:0                            metrics:nil                            views:NSDictionaryOfVariableBindings(button)];         [self.view addConstraints:constraints1];    [self.view addConstraints:constraints2];               UIButton *button1=[[UIButton alloc]init];    button1.translatesAutoresizingMaskIntoConstraints=NO;    [button1 setTitle:@"请不要点击我"forState:UIControlStateNormal];    [button1 setBackgroundColor:[UIColor redColor]];    [self.view addSubview:button1];         NSArray *constraints3=[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[button1]-|"                             options:0                            metrics:nil                            views:NSDictionaryOfVariableBindings(button1)];         NSArray *constraints4=[NSLayoutConstraint constraintsWithVisualFormat:@"V:[button]-[button1(==30)]"                            options:0                            metrics:nil                            views:NSDictionaryOfVariableBindings(button1,button)];         [self.view addConstraints:constraints3];    [self.view addConstraints:constraints4];     }

Run the following:

By comparing the code, we can see that we have made a little change in the vertical constraint of the button1. As with the button in the horizontal direction, there is not much explanation here. Let's take a look at the vertical direction.

1234 NSArray *constraints4=[NSLayoutConstraint constraintsWithVisualFormat:@"V:[button]-[button1(==30)]"                         options:0                         metrics:nil                         views:NSDictionaryOfVariableBindings(button1,button)];

The VFL statement is: @ "V:[button]-[button1 (==30)]", where two view is used inside the VFL statement. As we said earlier, "-" when used on the same level of view, the spacing is 8 pixels, the whole sentence means that the y-coordinate of the Button1 is 8 pixels from the button. When you do not use auto layout, you can express Cgrectgetmaxy ( Button.frame) +8.

I'm going to change the above sentence. The VFL

1234 NSArray *constraints4=[NSLayoutConstraint constraintsWithVisualFormat:@"V:[button]-[button1(==height)]"                         options:0                         metrics:@{@"height":@30}                         views:NSDictionaryOfVariableBindings(button1,button)];

Run again and you will find that the effect is the same. So you know how to dynamically add height or width to a view, or other spacing?

So, how to do two view, or multiple view between the high, or equal width? Can you do it with the VFL? In addition to the values of the above directly assigned width and height, the VFL also provides another way to use the equal-width equal height.

Or the above demo, we change the code

123456789 nsarray *constraints3=[nslayoutconstraint  constraintswithvisualformat:@ "H:|-[button1 (Button)]" options:0 Metrics:nil Views:nsdictionaryofvariablebindings (Button1,button)]; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;        nsarray *constraints4=[nslayoutconstraint  constraintswithvisualformat:@ "V:[button]-[button1 (Button)]" options:0 Metrics:nil Views:nsdictionaryofvariablebindings (Button1,button)];

Through @ "H:|-[button1 (button)", @ "V:[button]-[button1 (Button)]", these two sentences can easily achieve equal width and so on!

Set the distance between sibling view:

Horizontal button1 and button-like widths    nsarray *constraints3 = [Nslayoutconstraint constraintswithvisualformat:@ "h:|-[ Button1 (Button)] "options:0 metrics:nil views:nsdictionaryofvariablebindings (button,button1)];    Button1 the y-coordinate of the distance button is 8. And the height is the same as button1    //nsarray *constraints4 = [Nslayoutconstraint constraintswithvisualformat:@ "V:[button]-[button1 (Button)]" options:0 metrics:nil Views: Nsdictionaryofvariablebindings (Button,button1)];    Specifies the distance between the button of the sibling and the vertical direction between Button1 50. And the same height    nsarray *constraints5 = [Nslayoutconstraint constraintswithvisualformat:@ "V:[button]-50-[button1 (Button)]" options:0 metrics:nil Views: Nsdictionaryofvariablebindings (Button,button1)];    [Self.view Addconstraints:constraints3];    [Self.view ADDCONSTRAINTS:CONSTRAINTS4];    [Self.view ADDCONSTRAINTS:CONSTRAINTS5];

Three: Finally, the format of the string to make a summary introduction

Functional expressions

Horizontal direction H:

Vertical direction V:

views [view]

Superview |

Relationship >=,==,<=

Space, Gap-

Priority @value

I hope that the readers will be helpful, if the wrong place also hope to point out.

Using the VFL in Auto layout (Visual format language)-code for automatic layout

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.