iOS Development Diary 30-autolayout

Source: Internet
Author: User
Tags abstract language

Today Bo Master has a AutoLayout demand, met some difficulties, here and we share, hope to progress together.

1 . Overview

In the previous IOS program, how did you set up the layout UI interface?

(1) Often write a large number of coordinate calculation code

(2) In order to ensure that the 3.5 inch and 4.0 inch screen can have a perfect UI interface effect, and sometimes need to write a different coordinate calculation code for 2 screens (that is, the legendary "screen adaptation")

What is AutoLayout ?

(1) AutoLayout is a "auto-layout" technology designed to layout the UI interface

(2) AutoLayout since the introduction of iOS 6, due to the lack of power of Xcode 4, then did not get a big promotion

(3) since iOS 7 (Xcode 5), the development efficiency of AutoLayout has been greatly improved.

(4) Apple also recommends developers try to use AutoLayout to layout the UI interface

(5) AutoLayout can easily solve the problem of screen adaptation

autoresizing

(1) Before the AutoLayout, there are autoresizing can be used for screen adaptation, but the limitations are large, some tasks simply cannot be completed

(2) In contrast, AutoLayout has a much stronger function than autoresizing.

2 Core Concepts of AutoLayout:

(1) Reference

(2) Constraints

2 . AutoLayout warnings and Errors

Warning:

The control's frame does not match the constraint added, such as:

The width of the constraint control is 100, and the control now has a width of 110

Error:

Lack of necessary constraints, such as:

Constrain width and height only, no constraint-specific position

Two constraint conflicts, such as:

1 constrained controls have a width of 100, 1 constrained controls have a width of 110

3 , code implementation AutoLayout

The code implements AutoLayout steps:

Step one: Create a specific constraint object using the Nslayoutconstraint class

Step two: Add the constraint object to the corresponding view

-(void) AddConstraint: (Nslayoutconstraint *) constraint;

-(void) Addconstraints: (Nsarray *) constraints;

The code implements the AutoLayout point of attention:

(1) To prohibit the Autoresizing function, set the view below the property is no

View.translatesautoresizingmaskintoconstraints = NO;

(2) Before adding constraints, make sure that the relevant controls are already on the respective parent control

(3) no need to set frame to view

4 , nslayoutconstraint

A Nslayoutconstraint object represents a constraint.

Common ways to create constrained objects:

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

View1: The control to constrain

ATTR1: Type of constraint (how to constrain)

Relation: Relationship to the reference control

VIEW2: Referenced controls

ATTR2: Type of constraint (how to constrain)

Multiplier: Multiplier

C: constant

Automatic layout has a core formula:

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

For example: Achieve the following effect:

-(void) viewdidload{[Super Viewdidload];  1. Adding controlsUIView *blueview = [[UIView alloc] init];Blueview.backgroundcolor = [Uicolor Bluecolor];Blueview.translatesautoresizingmaskintoconstraints = NO;[Self.view Addsubview:blueview];UIView *redview = [[UIView alloc] init];Redview.backgroundcolor = [Uicolor Redcolor];Redview.translatesautoresizingmaskintoconstraints = NO;[Self.view Addsubview:redview]; 2. Constrained Blue 2.1. Height Nslayoutconstraint *blueheight =[nslayoutconstraint constraintwithitem:blueview attribute: Nslayoutattributeheight relatedby:nslayoutrelationequal Toitem:nil Attribute:nslayoutattributenotanattribute Multiplier1.0constant:40];[Blueview Addconstraint:blueheight]; 2.2. Left pitchCGFloat margin =20; Nslayoutconstraint *blueleft =[nslayoutconstraint Constraintwithitem:blueview attribute:nslayoutattributeleft Relatedby:nslayoutrelationequal Toitem:Self.view Attribute:nslayoutattributeleft Multiplier:1.0 Constant:margin];[Self.view Addconstraint:blueleft]; 2.3. Top pitch nslayoutconstraint *bluetop =[nslayoutconstraint constraintwithitem:blueview attribute: Nslayoutattributetop relatedby:nslayoutrelationequal Toitem:Self.view Attribute:nslayoutattributetop Multiplier:1.0 Constant:margin];[Self.view Addconstraint:bluetop]; 2.4. Right pitch nslayoutconstraint *blueright = [Nslayoutconstraint constraintwithitem:blueview attribute: Nslayoutattributeright relatedby:nslayoutrelationequal Toitem:Self.view Attribute:nslayoutattributeright Multiplier:1.0 Constant:-margin];[Self.view Addconstraint:blueright]; 3. Constraint red 3.1. Let Red right = = Blue Right nslayoutconstraint *redright =[nslayoutconstraint Constraintwithitem:redview attribute: Nslayoutattributeright relatedby:nslayoutrelationequal Toitem:blueview attribute:nslayoutattributeright Multiplier :1.0constant:0.0];[Self.view Addconstraint:redright]; 3.2. Let the red height = = Blue Height nslayoutconstraint *redheight =[nslayoutconstraint constraintwithitem:redview attribute: Nslayoutattributeheight relatedby:nslayoutrelationequal Toitem:blueview Attribute:nslayoutattributeheight Multiplier1.0 constant:0.0]; [self.view addconstraint:redheight]; //3.3. Make red top = = Blue Bottom + pitch nslayoutconstraint *redtop =[nslayoutconstraint constraintwithitem:redview attribute : Nslayoutattributetop relatedby:nslayoutrelationequal Toitem:blueview Attribute:nslayoutattributebottom Multiplier : 1.0 Constant:margin];  [self.view addconstraint:redtop]; //3.4. Let the red width = = Blue Width * 0.5NSLayoutConstraint *redwidth =[nslayoutconstraint Constraintwithitem: Redview attribute:nslayoutattributewidth relatedby:nslayoutrelationequal toitem:blueview attribute: Nslayoutattributewidth multiplier:0.5 Constant:0.0]; [self.view addconstraint:redwidth];}          

5 . Rules for adding constraints

After you create a constraint, you need to add it to the action view.

Be aware that the following rules apply to the target view when adding:

(1) For a constraint relationship between two view levels, add to their parent view

(2) for the constraint relationship between two different levels of view, add to their nearest common parent view

(3) For a hierarchical relationship between the two view constraints, added to the higher level of the parent view

6 . the VFL language

What is the VFL language?

The VFL's full name is Visual format Language, which translates to "visual formatting language", an abstract language that Apple has introduced to simplify AutoLayout coding.

7 . Example of the VFL

H:[cancelbutton (]-12-[acceptbutton) (50)]

Canelbutton width 72,acceptbutton Width 50, spacing between them 12

H:[wideview (>[email protected])

Wideview width greater than or equal to 60point, the constraint priority is 700 (the priority is the maximum of 1000, the higher the precedence of the constraint is satisfied first)

V:[redbox]-[yellowbox (==redbox)]

In the vertical direction, there is a redbox, immediately below a height equal to Redbox height Yellowbox

H:|-10-[find]-[findnext]-[findfield (>=20)]-|

Horizontally, find is the default interval width for the left edge of the parent view, followed by the default width of FindNext distance from the find interval, followed by a findfield with a width of not less than 20, which is the default width of FindNext and the right edge of the parent view. (Vertical bar "|" indicates the edge of the Superview)

8 . Use of the VFL

Use the VFL to create an array of constraints:

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

FORMAT:VFL statements

OPTS: Constraint type

The specific values used in the METRICS:VFL statement

The controls used in the VIEWS:VFL statement

Create a shortcut macro definition for a dictionary that contains the controls used within the VFL statement:

Nsdictionaryofvariablebindings (...)

For example:

Nsdictionary *views =

Nsdictionaryofvariablebindings (Blueview, Redview);

Nsarray *conts2 =

[Nslayoutconstraint Constraintswithvisualformat:

@ "V:[blueview (==blueheight)]-margin-|" options:0 metrics:

@{@ "Blueheight": @40, @ "margin": @20} Views:views];

Example code:

-(void) viewdidload{[Super Viewdidload];  //1. Adding controlsUIView*blueview = [[UIView alloc] init];Blueview.backgroundcolor = [Uicolor Bluecolor];Blueview.translatesautoresizingmaskintoconstraints = NO;[Self.view Addsubview:blueview];UIView*redview = [[UIView alloc] init];Redview.backgroundcolor = [Uicolor Redcolor];Redview.translatesautoresizingmaskintoconstraints = NO;[Self.view Addsubview:redview]; //2.VFL Build Constraint Nsarray*conts = [Nslayoutconstraint constraintswithvisualformat:@ "h:|-20-[blueview]-20-| "options:0 metrics:nil views:@{@" Blueview ": Blueview}";  [Self.view addconstraints:conts]; Nsarray *conts2 = [nslayoutconstraint constraintswithvisualformat:@ " V:|-20-[blueview (+)]-20-[redview (==blueview)] "Options:nslayoutformatalignallright Metrics:nil Views:@{@ "Blueview@ "Redview": Redview}]; [Self.view addconstraints:conts2]; Nslayoutconstraint *redwidth = [Nslayoutconstraint constraintwithitem:redview attribute: Nslayoutattributewidth relatedby:nslayoutrelationequal Toitem:blueview attribute:nslayoutattributewidth Multiplier : 0.5 constant:0.0];  [Self.view addconstraint:redwidth];}}         

Run:

9 , with the AutoLayout of the UILabel

Before AutoLayout, Uilabel's text content is always centered, resulting in a large open area at the top and bottom:

With AutoLayout, Uilabel's bounds will automatically wrap all text content on the default, and there will no longer be any vacant areas at the top and bottom:

AutoLayout - based animation

After you modify the constraint, you can animate it by simply executing the following code:

[UIView animatewithduration:1.0 animations:^{

[View layoutifneeded with constraint added];

}];

For example:

100;  200;[ animatewithduration://parent control and Redview all added constraints [Self.view layoutifneeded]; [Self.redview layoutifneeded];}];    

iOS Development Diary 30-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.