AutoLayout Code Layout Use Daquan-a new layout idea

Source: Internet
Author: User

After believing that iOS8 came out, many iOS programmers fret about the adaptation of the screen. I believe a lot of people know there are autolayout.

This thing can be a screen fit, in fact, AutoLayout is not just a tool for multi-screen adaptation,

Its real meaning is to give the programmer a new layout idea.

This article mainly according to the real project example from three directions omni-directional explanation AutoLayout's use Daquan.

One. AutoLayout layout Principles and syntax

Two. Constraint conflicts and AutoLayout animation processing

Three. AutoLayout layout thought, constraint chain control.

The content and code explained in this article is mainly dependent on a classification named uiview+autolayout. A download link will be attached at the end of the article.

One. AutoLayout layout Principles and syntax

Before writing this article, I read a lot of articles about AutoLayout tutorials. One sentence is particularly profound,

Before learning AutoLayout, it is necessary to abandon the traditional frame property completely, and to complete the twist of thought before learning to do more.

AutoLayout is something Apple ios6, unlike the traditional frame property. Each of the view objects has a frame property,

Frame belongs to the CGRect object, through the Apple API can be learned that cgrect is actually a structure.

struct CGRect {

Cgpoint origin;

Cgsize size;

};

typedef struct CGRECT CGRect; one is the cgpoint of the control coordinates, one is the cgsize of the control size.

The AutoLayout is implemented by the constraints of the layout. Once a view has used the AutoLayout constraint,

Then its frame will always be 0.

So two preparations are required before using AutoLayout.

1. Settings

Translatesautoresizingmaskintoconstraints is No.

2. If the Viewcontrol is a AutoLayout, write the

-(void) in updateviewconstraints.

If it is a view then AutoLayout is written in

-(void) in updateconstraints. In fact, this is one of the AutoLayout benefits that can focus on a controller and

The view is adapted in one method.

AutoLayout syntax is divided into three main categories

1. Set the size.

Let's take a look at the implementation of Uiview+autolayout.

[VIEWAUTOSETDIMENSION:ALDIMENSIONWIDTHTOSIZE:30];

The realization of the uiview+autolayout underlying native

Nslayoutconstraint *constraint = [NSLayoutConstraintconstraintWithItem:selfattribute:NSLayoutAttributeWidth

Relatedby:nslayoutrelationequal

Toitem:nilattribute:nslayoutattributenotanattributemultiplier:0.0fconstant:size];

[View Addconstraint:constraint];

Any AutoLayout syntax is added to the view constraint by creating a Nslayoutconstraint constraint object.

Creating a AutoLayout requires seven parameters, respectively (1) Withitem: Constrained object

(2) First attribute: The relationship of the constrained object (3) Relatedby: Constraint description (

4) Toitem: Constraint Source (5) Second attribute: Constraint source relationship (6) Multiplier: Constraint factor

(7) Constant: Constraint constants

In the official API, there is a calculation formula for the constraint

/* Create constraints explicitly. Constraints is of the form "VIEW1.ATTR1 = view2.attr2 * multiplier + constant"

The corresponding properties of the parameters in the Nslayoutconstraint API are explained below.

Typedefns_enum (Nsinteger, Nslayoutattribute) {

Nslayoutattributeleft = 1,

Nslayoutattributeright,

Nslayoutattributetop,

Nslayoutattributebottom,

Nslayoutattributeleading,

Nslayoutattributetrailing,

Nslayoutattributewidth,

Nslayoutattributeheight,

Nslayoutattributecenterx,

Nslayoutattributecentery,

Nslayoutattributebaseline,

Nslayoutattributelastbaseline =nslayoutattributebaseline,

Nslayoutattributefirstbaselinens_enum_available_ios (8_0),

Nslayoutattributeleftmarginns_enum_available_ios (8_0),

Nslayoutattributerightmarginns_enum_available_ios (8_0),

Nslayoutattributetopmarginns_enum_available_ios (8_0),

Nslayoutattributebottommarginns_enum_available_ios (8_0),

Nslayoutattributeleadingmarginns_enum_available_ios (8_0),

Nslayoutattributetrailingmarginns_enum_available_ios (8_0),

Nslayoutattributecenterxwithinmarginsns_enum_available_ios (8_0),

Nslayoutattributecenterywithinmarginsns_enum_available_ios (8_0),

Nslayoutattributenotanattribute =0

};

The above is the official API's description of the constraint relationship, where nslayoutattributeleading,nslayoutattributetrailing, in fact, is equivalent to left and right, and is said to be a habit of use in the Arab world. According to the above enumeration can see the constraint relationship is mainly up and down, width, height, horizontal center, ordinate center.

Typedefns_enum (Nsinteger, nslayoutrelation) {

Nslayoutrelationlessthanorequal =-1,

nslayoutrelationequal = 0,

Nslayoutrelationgreaterthanorequal = 1,

};

The constraint description is mainly <= = = >= is mainly used for uncertain size and coordinate constraints, the flexibility and dynamics of AutoLayout adaptation are mainly derived from this constraint relationship. The constraint coefficients multiplier and constraint constants constant mainly calculate the final result of the constraint relationship, following the formula "VIEW1.ATTR1 = view2.attr2 * Multiplier + constant" is the constraint source for all layouts, Can see very convenient to use, because to want to accurately a view dynamic layout, sometimes need to set several constraints to locate the location of the view, so this code is often more verbose than the set frame, fortunately, the introduction of the uiview+     AutoLayout can share it for you. Regression theme, through the above code can be seen, because only need to set the size of a view, so do not need to constrain the source, Toitem set to nil, then the relationship between the source of constraint is naturally no relationship,   The second attribute is set to Nslayoutattributenotanattribute. According to this kind of thinking, we can actually bind a view and the size of another view dynamically, but it is seldom used in this way.    I'll talk about it later.   2. The constraints between the positions first look at the implementation of Uiview+autolayout.   [View1autopinedge:aledgelefttoedge:aledgeleftofview:view1withoffset:5]; The realization of the uiview+autolayout underlying native

Nslayoutconstraint *constraint = [nslayoutconstraintconstraintwithitem:self

Attribute:NSLayoutAttributeLeftrelatedBy:NSLayoutRelationEqual
Toitem:view2attribute:nslayoutattributeleftmultiplier:1.0fconstant:5];

[View1 Addconstraint:constraint];

According to the meaning of each parameter explained above, the above method means that the leftmost distance of the constraint View1 to View2 is 5 (because the constraint coefficient is 1).

3. Constrain alignment

Let's take a look at the implementation of Uiview+autolayout.

[View1autoalignaxistosuperviewaxis:alaxisvertical];

The realization of the uiview+autolayout underlying native

Nslayoutconstraint *constraint = [NSLayoutConstraintconstraintWithItem:selfattribute:NSLayoutAttributeCenterX

Relatedby:nslayoutrelationequa ToItem:view1.superview

ATTRIBUTE:NSLAYOUTATTRIBUTECENTERXMULTIPLIER:1.0FCONSTANT:0.0F];

According to the meaning of the parameters explained above, the meaning of the above method is to constrain the center of the View1 in the parent view of View1.


As previously mentioned, all constraints are created by creating an identical Nslayoutconstraint object. So the code is chase small easy.

The following is a brief explanation of how the Uiview+autolayout classification is used.

According to the above constraint three kinds of uses, the uiview+autolayout corresponding method main body also divides into three kinds.

1. Set the size class (starting with Autosetdimension)


The following is the Aldimension enumeration

Typedefns_enum (Nsinteger, aldimension) {

Aldimensionwidth =nslayoutattributewidth,//The width of the view

Aldimensionheight =nslayoutattributeheight//The height of the view

};

2. Position constraint (starting with Autopin)

The following is the Aledge enumeration

Typedefns_enum (Nsinteger, Aledge) {

Aledgeleft =nslayoutattributeleft,//The left edge of the view

Aledgeright =nslayoutattributeright,//The right edge of the view

Aledgetop =nslayoutattributetop,//The top edge of the view

Aledgebottom = Nslayoutattributebottom,//The bottom edge of the view

aledgeleading = nslayoutattributeleading,//The leading edge of the view (left edge for left-to-right languages like 中文版, right edge for right-to-left languages like Arabic)

aledgetrailing = nslayoutattributetrailing//The trailing edge of the view (right edge for Left-to-right languages Li Ke 中文版, left edge for Right-to-left languages like Arabic)

};

3. Constraint alignment (autoalign start)

The following is the Alaxis enumeration

Typedefns_enum (Nsinteger, Alaxis) {

Alaxisvertical = Nslayoutattributecenterx,//a vertical line through the center of the view

Alaxishorizontal = Nslayoutattributecentery,//a horizontal line through the center of the view

Alaxisbaseline = nslayoutattributebaseline//A horizontal line at the text baseline (not applicable to all views)

};

The first section summarizes: mainly explains the AutoLayout bottom realization principle and the uiview+autolayout encapsulation principle.


Two. AutoLayout constraint conflicts and animation processing



The above page is a fully used AutoLayout layout, the overall structure is this, the top of the Label1 and the upper right button button1,

The middle of the imageview1 and Label2, below two cellview1 and Cellview2, then a button2,

The bottom tip is negligible.

Cellview1 and Cellview2 are custom view, and some of the image view and label are its child view.

Focus: When a parent view1 has a child view2, and the child View2 has a child view3, then when the constraint view3,

If its parent view is not the top-level view, then the VIEW3 constraint will have a constraint on its parent view.

This rule is really difficult to find out the mind, I do not elaborate here, I hope the reader in the face of constraint conflict

Gradually get to the rule.

AutoLayout animation processing.

If a view is using the AutoLayout constrained layout, this time if the view is animated,

According to the traditional practice is to change some of its properties, in the translation animation is mainly to change its frame coordinates,

But in AutoLayout, frame is 0 how to deal with it. Here the author from difficult to easy to provide three kinds of solutions.

1. Using the [self.viewlayoutifneeded] method to dynamically refresh the constraints, the author believes that the beginner AutoLayout of the People

Is the hardest thing to do.

2. Change the bounds property of the view. This online has information, in AutoLayout the bounds attribute is valid.

This may be a relatively good solution.

3. Change the Transform property of the view, for example, 10 distance on the net, can write Self.transform = cgaffinetransformmaketranslation (0,-10); Believe this is the simplest and best to deal with.

Three. AutoLayout layout thought, control of constraint chain

or use this page plus uiview+autolayout to explain in detail.

For example, I want to layout cellView1 the most left of the merchant bank logo ImageView.

Use Uiview+autolayout to write this.

[ImageView autopinedge:aledgetop toedge:aledgetop ofview:self Withoffset:5];

[ImageView autopinedge:aledgeleft toedge:aledgeleft ofview:self Withoffset:5];

[ImageView autopinedge:aledgebottom toedge:aledgebottom ofview:self Withoffset:5];

[ImageView autopinedge:aledgeright toedge:aledgeleft ofview:self withoffset:35];

Basically any view can use four position constraints on its upper and lower sides to determine its position,

The meaning of these four lines of code is

ImageView top distance between top of parent view 5,image view bottom distance from parent view Bottom 5,

ImageView left distance from parent view 5,imageview right distance from parent view left 35,

In this case, if the height of the parent view is 40, then the size of the ImageView does not need to be set,

Naturally, these four constraints are (30,30).

This looks like nothing wrong, and it's actually too much of a restraint. When the height of the parent view is changed,

The height of the ImageView is calculated dynamically due to the constraints on the top and bottom, if the parent view is 50 higher,

Then ImageView size is (30,40), this time if it is a square picture will be deformed,

In fact, this is not the essence of AutoLayout.

Let's look at the following constraint pattern.

[Imageviewautosetdimensionstosize:cgsizemake (30,30)];

[Imageviewautopinedge:aledgelefttoedge:aledgeleftofview:selfwithoffset:5];

[Imageviewautoalignaxistosuperviewaxis:alaxishorizontal];

These three lines of code mean the fixed size of the constraint ImageView (30,30),

Constraint ImageView The left margin of the parent view is 5, and the ordinate axis of the constraint ImageView is aligned with the parent view ordinate axis.

The above three constraints are not difficult to see, regardless of the parent view if the change in size and position,

The shape of the image itself and the relative position of the parent view are fixed.

Summary: AutoLayout Real Grammar Only one method, as long as the understanding of the method of the seven parameters represented by the meaning of the AutoLayout is not difficult to understand the principle of implementation. So for programmers, the important thing is not how long this layout is written in code, because there are a lot of three-way library can help you shorthand code, in fact, we really want to grasp the AutoLayout of this layout idea, in the heart of a view layout when the heart should have a constraint chain , your layout constraints will be more streamlined, more accurate, and more adaptable.

Because the author himself is just contact AutoLayout, above is just a rough explanation of their own learning experience, I strongly recommend uiview+autolayout this library to use AutoLayout, because the package is more image, and close to the bottom, To understand the principle of autolayout and grasp the connotation of more beneficial.

AutoLayout Code Layout Use Daquan-a new layout idea

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.