Visual format language in AutoLayout

Source: Internet
Author: User

First, when to use AutoLayout more suitable


1. Irresponsible fence: Apple has a growing number of devices and your app should use AL. (And with SB)


2. To see the application content decision. If your content is informative, there are a lot of categories to show, and the dimensions are dynamic and even these are in the list. (such as social apps). Al can give a lot of help.


Application of 3.Mac OS. Now it's all done with iOS. Mac app's window, there will be size changes. Al is more appropriate.


4. Support multi-turn screen ipad app. (Is there a need to support multiple iphone scenarios?) So long, brain-crippled? )


5. Other business is not complex, page less application, in fact, cocoa programmers have written for many years code has their own UI programming habits, these habits for them is very efficient. Even the first one says that the coordinates of the layout are relative.


If you are accustomed to code writing layouts, it is recommended that you continue to follow and also learn al. Self-feeling Al and traditional layout, the workload will not vary too much. But the VFL will have a great improvement after being skilled.


Two. The basic theory of AutoLayout


Al's core point of departure is


1.view has the ability to calculate size and layout of the self. The size can be obtained through its own content.


The layout position of the 2.view is determined by its relationship to Superview and other view.


3. Compared to the traditional Autoresizingmask adaptive, Al is more precise and can definitely determine the layout of the view.


The 4.view does not necessarily require an initial rect. In AL, if the view has enough constraint, it can determine its size and location, and know its relationship to other view. That is, to determine the layout of the view, add constraint to it.


Three. AutoLayout under the Xib


It seems that the AL and Xib layout patterns were born to be together. Using Xib plus Al,view layout is easy and easy. Programming work immediately became the art of online jigsaw puzzles.


After you turn on Xib or SB, choose View (s). Select the Editor for menu and select PIN. The submenu item is the available constraints.

Width: fixed self width


Height: ...


H-spacing: Fixed Two-view horizontal spacing


V-spacing: ...


The following 4 are the left, right, top, and bottom spacing of view relative to Superview


Widths equally: Two view remains the same width


Heights equally: ...


Xib the lower right corner of the interface toolbar also has the way to edit the constraint:

Each constraint can be edited after it has been added. After selecting a constraint, open the right column and select Inspector. You can modify the values. (This value is the offset between the view) and the priority level.


Slowly dragged himself to play. This is not a fool tutorial. Point in place and study for yourself.


Al is more intuitive under xib. You can basically see the effects and error values. There are also incorrect hints for constraint. Less constraint compiler will fill, more will prompt an error. (but will cause the interface layout is not correct, oneself slowly adjust, elder brother now still is full article alert, did not let the compiler feel contradictory puzzling constraint, all can work. )


There are resolve ways to solve the constraint problem, sorry, I will not.


Four. Use the AutoLayout encoding method


For common applications where there are not many pages. Xib/sb and Al. Drag and drop. The UI work can be done in entertainment. Al did give a lot of convenience.


But for years of obsessive-compulsive disorder, apes have endured this lame way. (Tow blocks?) Don't hit the code? It seems like a day without work. )


1.Visual Formatlanguage (should not be counted as language)

Apple's engineers have loved to invent this kind of hieroglyphs. Feel it is an analytic way.


Apple's official documentation gives a few examples of documents and pits. (video I did not see, do not know how) on-line students have also written a little bit of a few words of code. Are you learning the rhythm of calculus? It is better not to write or write clearly than to write.


From the kind of foreigner that saw a few. I have experienced some, share to everyone. Just a basic level, it will be, the code to write Al should be no problem. In-depth I also do not want to meet more love of the cattle to share.


The VFL is supported in the program by:


+ (Nsarray *) Constraintswithvisualformat: (NSString *) format options: (nslayoutformatoptions) OPTs metrics: ( Nsdictionary *) Metrics Views: (Nsdictionary *) views;



-it returns a set of constraint.

-Format is your VFL string, and so on.


-OPTs yourself point to the head file to see. Some cases will be used, wait for an example.


-metrics is a wonderful dictionary that you define yourself. The key in this dictionary can be written in the format string. When the compiler resolves, it is automatically replaced with value in the Metrics dictionary. Wait for an example.


-Views are all views that require a constraint relationship. (can also be a)


2.VFL Example

When writing the VFL string, imagine the rationality of the picture in your mind. Unreasonable constraint can cause the program to run the Times wrong or crash directly.


Write a few.


Nsdictionary *dict1 = nsdictionaryofvariablebindings (_BOXV,_HEADERL,_IMAGEV,_BACKBTN,_DONEBTN);

Nsdictionary *metrics = @{@ "hpadding": @5,@ "vpadding": @5,@ "Imageedge": @150.0};

NSString *VFL = @ "|-hpadding-[_boxv]-hpadding-|";

NSString *vfl0 = @ "V:|-25-[_BOXV]";

NSString *vfl3 = @ "V:|-vpadding-[_headerl]-vpadding-[_imagev (imageedge)]-vpadding-[_backbtn]-vpadding-|";


Dict1 is the last parameter you need in the API. This is done by the macro above.


Metrics defines some of the parameters to be used in the VFL.


Below are some of the VFL strings, which let you know how to use metrics.


See:


1) "|" Represents Superview.


|-Spacing-[view1 Object name-(>=20)-[view2 object name]


Do not write h/v means horizontal, spacing can write fixed value also can write >/<.


Visualize the understanding, "|" is used to determine the top, bottom, left, and right relationships of a view.


To determine the relationship from top to bottom, add v:|. Then the VFL string can describe the relationship between the top and bottom view.


2) See vfl3 inside, square brackets represent view, parentheses denote dimension values. Support size equals. Or the width of another view |-[view1 (VIEW2)],V1 is equal to V2.


3) Priority is denoted by @. such as V:|[email Protected][view (55)], or write to metrics inside better.


See Uilayoutpriority for specific definitions. There are several fixed values. 1000 indicates that support is required.


4) Options, this depends on the specific needs. If it's a vertical v-layout, you can add nslayoutformatalignallleft and let them align.


You can also add a bitwise OR NSLAYOUTFORMATALIGNALLLEFT as needed | Nslayoutformatalignallright. (The ghost knows what needs, oneself see experience bar)


5) After writing, generally add constraint to Superview:


NSString *VFL1 = @ "|-hpadding-[_headerl]-hpadding-|";

[Self.view addconstraints:[nslayoutconstraint constraintswithvisualformat:vfl1 options:0 metrics:metrics Views: Dict1]];



6) There is also an API for generating a single constaint


+ (ID) Constraintwithitem: (id) view1 attribute: (nslayoutattribute) attr1 Relatedby: (nslayoutrelation) Relation Toitem :(id) view2 attribute: (nslayoutattribute) attr2 multiplier: (cgfloat) Multiplier constant: (cgfloat) C;


For parameters, remember, view1.attr1 = view2.attr2 * Multiplier + constant is good.

This is not the VFL, good understanding, but inconvenient. If you write with this. Work two is no less than the traditional layout.


Five. Problems in the actual operation

The above are all theories, the world operation will have some strange problems to pay attention to. This is the focus of the day.


Xib mode, nothing to pay attention to, Xib in the newspaper warning, I do not know how to do, everything is fine.


Encoding mode,

1.addConstraint (s) before the view should be addsubview up.

2. Do not write frame to views

3. Turn off the autoresizeingmask for the necessary view. [_aviewsettranslatesautoresizingmaskintoconstraints:no];

4.UILabel line to write Linebreakmode, to write NumberOfLines (iOS7.0 default seems to be 1, pit dad)

5.UILabel to change lines, be sure to add preferredmaxlayoutwidth. Otherwise, the width cannot be initialized.


The maximum convenience that the coding mode feels. Label wrapping does not have to be calculated by line height. Fully automatic adaptation. The Superview that the label is in also automatically calculates the Rect. This is the essence of al.


So, you don't have to write this:


[OBJC] View plaincopy



I have some problems that have not been solved so far:


The plain code-written Viewcontroller does not display the Al layout properly. With a blank xib VC, the rest of the code to write, it is normal. Doubts about the self.view you write, and what you need to do with AutoLayout. At this point, AL, the basic functions are already available for you. Indeed, it is convenient to use the VFL code pattern, which makes it much more efficient to be proficient.


[Nslayoutconstraint Constraintswithvisualformat:

Options:metrics:

Views

];


Constraintswithvisualformat: The parameter is nsstring type, specifies the attribute of the Contsraint, is the qualification of the vertical direction or the horizontal direction, the parameter definition is generally as follows:


v:|-(>=xxx): Indicates a distance greater than, equal to, or less than superview in the vertical direction


If you want to define a horizontal direction, change V: to H: you can


The height/width of the current view/control is set in the brackets in the back-[] bracket.


Options: The value of the dictionary type, where the value is typically selected in a system-defined enum


Metrics:nil; general nil, parameter type nsdictionary, external incoming//measurement standard


Views: Is the binding view added to the nsdictionary above


Note Here is the difference between addconstraints and AddConstraint, an added parameter is Nsarray, one is Nslayoutconstraint


Usage rules


|: Represents the parent view


-: Indicates distance


V:: Indicates vertical


H:: Indicates level


>=: Indicates that the view spacing, width, and height must be greater than or equal to a value


<=: Indicates that the view spacing, width, and height must be small or equal to a value


= =: Indicates that the view spacing, width, or height must be equal to a value


@: >=, <=, = = limit maximum of 1000



1.|-[view]-|: The view is within the left and right edges of the parent view


2.|-[view]: View is in the left edge of the parent view


3.| [view]: Align the view to the left of the parent view


4.-[view]-: Setting the width height of the view


5.|-30.0-[view]-30.0-|: Indicates left and right distance from parent view 30


6.[view (200.0)]: Indicates a view width of 200.0


7.|-[view (View1)]-[view1]-| : Represents the width of the view and is within the left and right edges of the parent view


8. V:|-[view (50.0)]: view height is 50


9:v:|-(==padding)-[imageview]->=0-[button]-(==padding)-|: Indicates the distance from the parent view


For padding, the two view spacing must be greater than or equal to 0 and the distance from the bottom parent view is padding.


: [Wideview (>[email protected]): The width of the view is at least 60 and cannot exceed 700, and the maximum is 1000


11: If no declaration direction defaults to horizontal V:



Auto Layout Simple Application



Auto layout was introduced to iOS on WWDC2012 and supported since iOS6.0, but most developers are accustomed to using traditional UI layouts, although a large number of developers have already used auto layout, Most of these developers choose to use Auto layout when dragging an IB file or using Storyboard.

Auto layout is a constraint-based, descriptive layout system. That is, using constraints to describe the layout, the view frame is calculated based on these descriptions.

A new class was added after iOS6.0: Nslayoutconstraint. We can create constraints in a Visual format language (as described later in the article) using visual formatting Language, which is also a way to create, as described later in this article. This method is as follows:


[CPP] View plaincopy

+ (Nsarray *) Constraintswithvisualformat: (NSString *) format options: (nslayoutformatoptions) OPTs metrics: ( Nsdictionary *) Metrics Views: (Nsdictionary *) views;

We can use this method to achieve the layout of the following effects:

The implementation of the code is as follows, the comments are written in their own understanding, what is wrong, please comment.


[CPP] View plaincopy

if (Floor (nsfoundationversionnumber) > Nsfoundationversionnumber_ios_6_1)
{
Self.edgesforextendedlayout = Uirectedgenone;
}

Automatic layout
Normal Create button, but do not set the Frame property of the button
UIButton * LeftButton = [UIButton Buttonwithtype:uibuttontypesystem];
LeftButton.layer.borderWidth = 2.0;
LeftButton.layer.borderColor = [Uicolor blackcolor]. Cgcolor;
[LeftButton settitle:@ "left" forstate:uicontrolstatenormal];
[Self.view Addsubview:leftbutton];

UIButton * Rightbutton = [UIButton Buttonwithtype:uibuttontypesystem];
RightButton.layer.borderWidth = 2.0;
RightButton.layer.borderColor = [Uicolor blackcolor]. Cgcolor;
[Rightbutton settitle:@ "right" forstate:uicontrolstatenormal];
[Self.view Addsubview:rightbutton];

Turn off adaptive conversions to layout constraints (sometimes not required depending on the situation)
[LeftButton Settranslatesautoresizingmaskintoconstraints:no];
[Rightbutton Settranslatesautoresizingmaskintoconstraints:no];

Create an array that holds constraints
Nsmutablearray * tempconstraints = [Nsmutablearray array];


[Tempconstraints addobjectsfromarray:[nslayoutconstraint constraintswithvisualformat:@ "H:|-80-[leftButton (==60)] -30-[rightbutton (==60)] "options:0 metrics:nil views:nsdictionaryofvariablebindings (LeftButton,rightButton)]";


[Tempconstraints addobjectsfromarray:[nslayoutconstraint constraintswithvisualformat:@ "V:|-30-[leftButton (==30)] "Options:0 Metrics:nil views:nsdictionaryofvariablebindings (LeftButton)];

[Tempconstraints addobjectsfromarray:[nslayoutconstraint constraintswithvisualformat:@ "V:|-30-[rightButton (= = LeftButton)] "options:0 metrics:nil views:nsdictionaryofvariablebindings (Rightbutton,leftbutton)]];

To add a constraint to a view
[Self.view addconstraints:tempconstraints];




The point to note here is that when we add a created constraint to the view, the target view to be added follows the following rules:



For the constraint relationships between the two same-level view, add them to their parent view.
For the constraint relationship between two different levels of view, add to their nearest common parent view
For a hierarchical relationship between the two view constraints, added to the higher level of the parent view


Visual format language in AutoLayout

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: info-contact@alibabacloud.com 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.