AutoLayout code Layout-a brand new layout idea, autolayout Layout

Source: Internet
Author: User

AutoLayout code Layout-a brand new layout idea, autolayout Layout

I believe that many ios programmers are worried about screen adaptation after ios8. I believe many people know that there is AutoLayout.

In fact, AutoLayout is not just a tool for multi-screen adaptation,

The true significance of it is to give programmers a new idea of layout.

This article describes how to use AutoLayout in three ways based on real project instances.

I. AutoLayout layout principle and syntax

II. Constraint conflicts and AutoLayout animation Processing

3. The idea of AutoLayout layout controls the Constraint Chain.

The content and code described in this article mainly depend on a classification named UIView + AutoLayout. The download link will be attached at the end of the article.

 

I. AutoLayout layout principle and syntax

Before writing this article, I have read many articles about the AutoLayout tutorial. One sentence is particularly profound,

Before learning AutoLayout, you must completely discard the traditional frame attributes and complete reverse learning to get twice the result with half the effort.

AutoLayout is a product of Apple ios6, which is different from the traditional Frame attribute. Each view object has a frame attribute,

Frame is a CGrect object. It can be learned through Apple's Api that CGrect is actually a struct.

Struct CGRect {

CGPoint origin;

CGSize size;

};

Typedef struct CGRect; one is the CGPoint that controls coordinates, and the other is the CGSize that controls the size.

 

While AutoLayout implements layout through constraints. Once a view uses the AutoLayout constraint,

Then its frame will always be 0.

Therefore, two preparations are required before using AutoLayout.

1. Set

TranslatesAutoresizingMaskIntoConstraints is NO.

2. For viewControl, AutoLayout is applicable

-(Void) in updateViewConstraints.

For view, AutoLayout is applicable

-(Void) in updateConstraints. In fact, this is also one of the advantages of AutoLayout.

View is adapted to a method.

 

 

The AutoLayout syntax is divided into three types:

1. Set the size.

Let's take a look at the implementation of UIView + AutoLayout.

 

[ViewautoSetDimension: ALDimensionWidthtoSize: 30];

Native Implementation of UIView + AutoLayout

 

NSLayoutConstraint * constraint = [NSLayoutConstraintconstraintWithItem: selfattriwidth: NSLayoutAttributeWidth

RelatedBy: NSLayoutRelationEqual

ToItem: nilattribute: NSLayoutAttributeNotAnAttributemultiplier: 0.0 fconstant: size];

[View addConstraint: constraint];

Any AutoLayout syntax is added to view constraints by creating an NSLayoutConstraint constraint object.

 

To create an AutoLayout, seven parameters are required. They are (1) WithItem: Constrained object.

(2) first attribute: Relationship of the constrained object (3) relatedBy: constraint description (

4) toItem: constraint source (5) second attribute: constraint source relationship (6) multiplier: constraint Coefficient

(7) constant: constraint constant

In the official api, there is a formula for calculating the constraints.

/* Create constraints explicitly. Constraints are of the form "view1.attr1 = view2.attr2 * multiplier + constant"

 

The following describes the attributes of parameters in the NSLayoutConstraint API.

TypedefNS_ENUM (NSInteger, NSLayoutAttribute ){

NSLayoutAttributeLeft = 1,

NSLayoutAttributeRight,

NSLayoutAttributeTop,

NSLayoutAttributeBottom,

NSLayoutAttributeLeading,

NSLayoutAttributeTrailing,

NSLayoutAttributeWidth,

NSLayoutAttributeHeight,

NSLayoutAttributeCenterX,

NSLayoutAttributeCenterY,

NSLayoutAttributeBaseline,

NSLayoutAttributeLastBaseline = nslayoutattriattributebaseline,

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 description of the binding relationship of the official API. nslayoutattrieleeleading and NSLayoutAttributeTrailing are equivalent to left and right. They are said to be the habits of Arab countries. According to the above enumeration, we can see that the constraints are mainly upper and lower sides, width, height, horizontal coordinate center, and vertical coordinate center.

TypedefNS_ENUM (NSInteger, NSLayoutRelation ){

NSLayoutRelationLessThanOrEqual =-1,

NSLayoutRelationEqual = 0,

NSLayoutRelationGreaterThanOrEqual = 1,

};

The constraint description is mainly <==>= used for constraints with uncertain sizes and coordinates. The flexibility and dynamic nature of autolayout adaptation mainly comes from the constraint relationship. The constraint coefficients multiplier and the constraint constant are used to calculate the final result of the constraint relationship. The formula "view1.attr1 = view2.attr2 * multiplier + constant" and above are the constraint sources of all la S, it can be seen that it is very convenient to use. To accurately deploy a View dynamically, sometimes you need to set several constraints to locate the view location, therefore, this code is usually longer to write than to set the frame. Fortunately, the UIView + AutoLayout introduced in this article can be shared for you. Return to the topic. From the code above, you can see that because you only need to set the size of a view, you do not need to restrict the source. If toItem is set to nil, the relationship between the source and the source is naturally irrelevant, the second Attribute is set to NSLayoutAttributeNotAnAttribute. According to this kind of thinking, we can dynamically bind the size of one view and the other, but it is rarely used. Why? I will talk about it later. 2. Constraints between locations let's take a look at the implementation of UIView + AutoLayout. [View1autoPinEdge: ALEdgeLefttoEdge: ALEdgeLeftofView: View1withOffset: 5]; Native Implementation of UIView + AutoLayout

NSLayoutConstraint * constraint = [NSLayoutConstraintconstraintWithItem: self

Attribute: NSLayoutAttributeLeftrelatedBy: NSLayoutRelationEqual
ToItem: View2attribute: NSLayoutAttributeLeftmultiplier: 1.0 fconstant: 5];

[View1 addConstraint: constraint];

 

According to the meanings of the parameters described above, the above method means that the distance from the leftmost side of view1 to the leftmost side of view2 is 5 (because the constraint coefficient is 1 ).

 

3. constraint alignment

Let's take a look at the implementation of UIView + AutoLayout.

 

[View1autoAlignAxisToSuperviewAxis: ALAxisVertical];

Native Implementation of UIView + AutoLayout

NSLayoutConstraint * constraint = [NSLayoutConstraintconstraintWithItem: selfattribute: NSLayoutAttributeCenterX

RelatedBy: NSLayoutRelationEqua toItem: view1.superview

Attribute: NSLayoutAttributeCenterXmultiplier: 1.0 fconstant: 0.0f];

According to the meanings of the parameters described above, the above method means to constrain the abscissa center of view1 to center in the parent view of view1.


As mentioned above, all constraints are implemented by creating the same NSLayoutConstraint object. Therefore, the code is easy to use.

 

The following describes how to use the class UIView + AutoLayout.

Based on the preceding three purposes, the method subjects corresponding to UIView + AutoLayout are also divided into three types.

1. Set the size class (beginning with autosetdimension)


ALDimension Enumeration

 

TypedefNS_ENUM (NSInteger, ALDimension ){

ALDimensionWidth = NSLayoutAttributeWidth, // the width of the view

ALDimensionHeight = NSLayoutAttributeHeight // the height of the view

};

2. Location constraints (starting with autopin)

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 ages like English, right edge for right-to-left ages like Arabic)

ALEdgeTrailing = NSLayoutAttributeTrailing // the trailing edge of the view (right edge for left-to-right ages like English, left edge for right-to-left ages like Arabic)

};

 

3. constraint alignment (starting with autoAlign)

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)

};

 

 

 

Section 1: Describes the underlying implementation principle of AutoLayout and the encapsulation principle of UIView + AutoLayout.


II. AutoLayout constraint conflicts and animation Processing



The above page is completely in the AutoLayout layout. The overall structure is like this. label1 at the top and button1 at the top right corner,

The middle imageview1 and label2, the lower two cellview1 and cellview2, And the next one is button2,

The following tips are ignored.

Cellview1 and cellview2 are custom views, and some image views and labels in them are their subviews.

Note: when a parent view1 has a child view2 and a child view2 has a child view3, when view3 is restricted,

If its parent view is not the top view, the constraint of view3 will affect its parent view.

This rule is indeed difficult to understand. I will not elaborate on it here. I hope that readers will encounter a constraint conflict.

Gradually find out the rule.

 

AutoLayout animation processing.

Assume that a view uses AutoLayout to constrain the layout. In this case, if the view is animated,

The traditional approach is to change some of its attributes. In a translation animation, the main thing is to change its frame coordinates,

But in AutoLayout, what should I do if frame is 0. Here, the author provides three solutions from hard to easy.

1. Use the [self. viewlayoutIfNeeded] method to dynamically refresh constraints. I think this person is a beginner of AutoLayout.

Is the most difficult.

2. Change the bounds attribute of the view. There are materials on the Internet, and the bounds attribute is valid in AutoLayout.

This may be a better solution.

3. modify the transform attribute of the view. For example, you can write self by translating 10 distances online. transform = CGAffineTransformMakeTranslation (0,-10); I believe this is the simplest and best to handle.

 

3. AutoLayout layout, control of constraint chains

You can also add UIView + AutoLayout to the page for detailed explanation.

For example, I want to layout the Image view of the leftmost China Merchants Bank logo in cellview1.

You can use UIView + AutoLayout to write in this way.

 

[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 positional constraints on its top, bottom, left, and right to determine its position,

These four lines of code do not mean

The distance between the top of the imageview and the top of the parent view is 5. The distance between the bottom of the image view and the bottom of the parent view is 5,

The left margin of imageview is 5 from the left margin of parent view, and 35 from the right margin of imageview to the left margin of parent view,

In this case, if the height of the parent view is 40, you do not need to set the size of the imageview,

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

This seems nothing wrong. In fact, it is already over-constrained. When the height of the parent view changes,

The height of the imageview is dynamically calculated based on the constraints on the top and bottom. If the height of the parent view is 50,

The size of the imageview is (30, 40). In this case, if the image is a square image, it will be deformed,

In fact, this is not the essence of AutoLayout.

Let's look at the following constraints:

[ImageViewautoSetDimensionsToSize: CGSizeMake (30,30)];

[ImageViewautoPinEdge: ALEdgeLefttoEdge: ALEdgeLeftofView: selfwithOffset: 5];

 

[ImageViewautoAlignAxisToSuperviewAxis: ALAxisHorizontal];

The three lines of code mean to constrain the fixed size (30, 30) of the imageview ),

The distance between the left side of the imageview and the left side of the parent view is 5. the vertical axis of the imageview is aligned with that of the parent view.

The preceding three constraints show that, regardless of the size and position of the parent view,

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

Conclusion: The real Syntax of AutoLayout is only one method. It is not difficult to understand the implementation principle of AutoLayout as long as you understand the meaning of the seven parameters of this method. So what is important for programmers is not how lengthy the layout method is to write code, because there are a lot of third-party libraries that can help you briefly write code, in fact, what we really need to grasp is the layout idea of AutoLayout. When we are concerned about a view layout, we should have a Constraint Chain in our mind, your layout constraints will become more streamlined, more accurate, and more adaptive.

 

Because I have just come into contact with AutoLayout, the above is just a rough explanation of my learning experience. I strongly recommend the library UIView + AutoLayout to use AutoLayout, because the encapsulation is more image-like, it is close to the underlying layer, which is more helpful for understanding the principle and understanding the connotation of AutoLayout.

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.