iOS Automatic layout advanced usage and pure hand code constraint notation

Source: Internet
Author: User
Tags abstract language

This article focuses on a few of the top-level uses of the summaries I've encountered (I'm sure there are a lot more advanced ones, of course). Simple storyboard in the upper and lower constraints, fixed width of the use of what is not done here to repeat.

AutoLayout Automatic layout is iOS6 after the appearance, but in the beginning of a period of time people are not how to use, are first ticked off. Then, with the advent of 5s,iphone6 screens varied. Using multi-layer if to determine the size is completely unable to hold the start to learn automatic layout.

Before that, there was a autoresizing property called auto-scaling, which is used primarily for the relationship between a control and its own parent control. Only AutoLayout can actually establish a relationship in any of the two controls.

About Autoresizing

Autoresizing It is important to note that the constraints set in storyboard and the constraints set in the hand code are the opposite. Storyboard the right line of the dot in the graphic page and the line below means "fixed"

The enumeration in the Autoresizingmasks attribute commonly used in the hand code is flexible to "scale". So if you want to fix the distance between the right and the bottom, you should set the scalability constraints on the left and the top in the code.

1 yellowview.autoresizingmask = Uiviewautoresizingflexibleleftmargin | Uiviewautoresizingflexibletopmargin;

With AutoLayout, this auto-scaling is rarely used for a total of seven properties.

None, wide retractable, high retractable, left pitch retractable, right pitch retractable, up pitch retractable, bottom pitch scalable

Uiviewautoresizingnone = 0,

Uiviewautoresizingflexiblewidth = 1 << 1,

Uiviewautoresizingflexibleheight = 1 << 4,

Uiviewautoresizingflexibleleftmargin = 1 << 0,

Uiviewautoresizingflexiblerightmargin = 1 << 2,

Uiviewautoresizingflexibletopmargin = 1 << 3,

Uiviewautoresizingflexiblebottommargin = 1 << 5

Each enumeration value is a displacement enumeration, and you can pass multiple values in one line of code.

About the automatic recognition size of labels

Label wants to display this in the interface.

The meaning is that the following controls can be adjusted automatically based on the bottom of the label above.

This is not set with the SizeToFit, but with the constraints, the data changes in the program running immediately change the constraints, the size is changed immediately.

This design method is:

1. Set the left and upper constraints of the label, and then set the next maximum width constraint assumption is 150, the label inside the lines property set to 0 that is arbitrarily any number of lines. The text inside will be automatically wrapped and always displayed, and the label's background color is automatically matched.

2. But there is one more on the right. A piece of blue on the right side of the label is not tightly next to it. This is the time to select the width of the constraint and then to the right of the relation from the original Equal to less than or Equal. This time the left side of the constraint display changed to ≤.

After running the result is: It is clear to see the right side of the label next to each other.

3. But sometimes the data may be empty, and once the size of the empty label is squeezed out, the following controls are messy. So in order to ensure that even if the data is not empty space to keep the placeholder, find him set two height constraints, one is greater than or equal to a is less than equal, wrapped into a range. At this time to the above width of less than equal to change to equal.

Just like this, the effect of running a large amount of text and no text at this time is

Played a role in the Occupy position. Even if there is no place in the text.

About where constraints was looking.

The diagram on the left constraints some under the label node under the View node, what is the reason for determining constraints under which node?

is to see whether the constraint depends on other controls, if it is to set their own fixed width and height what is not related to others that is under their own. If you depend on who has set the spacing, the constraint is placed under the minimum common parent control of your own and dependent controls.

About hand code writing AutoLayout constraints

Storyboard interface inside the pull is convenient but not the bulk operation (Dong Platinum but original), if there are similar to the 30 small control, storyboard is too troublesome, hand code word a cycle will be finished

Hand code creation is the so-called seven-parameter long-like method of a sentence

Then add the constraint under the corresponding node, add one and add a group of two methods.

//height constraint (added to Yellowview body)Nslayoutconstraint *heightconstraint = [Nslayoutconstraint constraintwithitem:yellowview attribute: Nslayoutattributeheight relatedby:nslayoutrelationequal Toitem:nil Attribute:nslayoutattributenotanattribute Multiplier0.0constant -];        [Yellowview Addconstraint:heightconstraint]; //spacing constraint (added to Self.view body)CGFloat margin = -; [Self.view addconstraints:@[//left[Nslayoutconstraint Constraintwithitem:yellowview Attribute:nslayoutattributeleft relatedBy:NSLayoutRelationEqual ToItem:self.view Attribute:nslayoutattributeleft Multiplier:1.0Constant:margin],//Right[Nslayoutconstraint constraintwithitem:yellowview attribute:nslayoutattributeright relatedBy: Nslayoutrelationequal ToItem:self.view attribute:nslayoutattributeright Multiplier:1.0Constant:-margin],//Bottom[Nslayoutconstraint constraintwithitem:yellowview attribute:nslayoutattributebottom relatedBy: Nslayoutrelationequal ToItem:self.view Attribute:nslayoutattributebottom Multiplier:1.0Constant:-margin]];

A core formula is used here.

Obj1.property1 = (Obj2.property2 * multiplier) + constant value

Multiplier and constant are vector coefficients and offsets.

And to avoid the constraints of automatic scaling that are generated by the system, this sentence is usually added

System default this property is Yes

About the VFL language visual format Language, translated by "visual formatting language" is the abstract language Apple introduced in order to simplify the AutoLayout encoding, which is equivalent to playing hieroglyphs, and to write all in the string, encountering errors more difficult to tune, But relatively speaking, the code is much leaner. The other method provided by the system is then used when the constraint is added.
    Nsarray *contraints = [nslayoutconstraint constraintswithvisualformat:vfl options:kniloptions metrics:metrics Views: views];

The detailed syntax of the VFL can be found in official documents by searching for "Visual Format"

The above method is uploaded to the two parameters metrics and views are two dictionaries. (Dong Platinum original) The first dictionary metrics is used to tell the system which letter each value corresponds to.

The second dictionary of views is used to tell the inside of each of the controls corresponding to what is in the string

If all the controls in the entire VFL language are written in the original, you can use a macro instead

Multiple values can be separated by commas in parentheses

A third-party framework for commonly used hand code constraints

With masonry and uiview+autolayout.

The frame address is:

Https://github.com/Masonry/Masonry

Https://github.com/smileyborg/UIView-AutoLayout

Uiview+autolayout Frame

This is a lightweight framework relative to masonry, which is easy to get started, with a total of two files in it. Also very useful, all start with auto. For projects that constrain changes infrequently

Case USAGE:

Directly set the distance between the perimeter

[Self.yellowview autopinedgestosuperviewedgeswithinsets:uiedgeinsetsmake  //directly set the distance between the perimeter

Set three intervals, and then add a height,

[Self.yellowview autopinedgestosuperviewedgeswithinsets:uiedgeinsetsmake  //  make top constraint invalid    [Self.yellowview autosetdimension:aldimensionheight tosize: // Add yourself a height constraint, exactly four .

You can also set the size directly

[Self.yellowview autosetdimensionstosize:cgsizemake ()];

In short, there are a lot of usage, not introduced in this, is probably the code style. If you are interested, you can go to the GitHub address above for a closer look.

Masonry frame This frame is heavyweight inside a lot of files, difficult to get started, but with a skilled words than the above that bull X, suitable for the constraint to change the items frequently. Example code: Adding an interval constraint from four directions 20
[Yellowview mas_makeconstraints:^ (Masconstraintmaker * make) {        // make represents Yellowview         //  add constraint        make.edges.equalTo (self.view). insets (uiedgeinsetsmake  -  - ));    }];

The following is an update constraint, which is very convenient to automatically identify the upper left and right properties to change.

[Self.yellowview mas_updateconstraints:^ (Masconstraintmaker * make) {        Make.left.equalTo (self.view.mas_left ). Offset (+);        Make.top.equalTo (self.view.mas_top). Offset (+);        Make.right.equalTo (self.view.mas_right). Offset (--);        Make.bottom.equalTo (Self.view.mas_bottom). Offset (-);    }];

There are some other property usages.

Mainly the author sets the attribute comparison more This picture is excerpted from his GitHub and is interested to go to GitHub to look closely

About adding animations to constraint changes. Because the change of the constraint is not the same as the concept of the frame, it is not valid to put the constraint code in the block of the animation, write the constraint on it, and then wrap the layoutifneed in the block of the animation. The other point to note is that you need to rely on the constraints of the parent control to write after the parent control is added. What are the different views welcome comments. This blog all articles are original, reproduced please indicate the source

iOS Automatic layout advanced usage and pure hand code constraint notation

Related Article

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.