"iOS Development" multi-screen ruler automatic adaptation AutoLayout (pure code mode)

Source: Internet
Author: User

About AutoLayout, it was first introduced from IOS6.

The main function is to use constraints, the view relative layout, to adapt to different screen ruler of the transformation. A lot of information on the Internet is introduced Xib and storyboard, how to use AutoLayout, said that pure code using AutoLayout UI layout less and fewer. For those of me who are accustomed to the code UI layout, write a memo: what is AutoLayout? Use an official Apple definition.
AutoLayout is a constraint-based, descriptive layout system. Auto layout is a constraint-based, descriptive layout System.
Keywords:
    • Based on constraints-and the position and size of the previously defined frame, the position of the AutoLayout is defined by the so-called relative position constraints, such as the x-coordinate of the center of Superview, the y-coordinate is 10 pixels above the bottom of the screen, etc.
    • Descriptive-constraint definitions and individual view relationships are described using approaches similar to natural languages or visual languages (later mentioned)
    • The layout system-that is, the literal meaning, is responsible for the position of each element of the interface.
In summary, AutoLayout provides developers with a layout method that differs from the traditional placement of UI element locations. Previously, whether you were dragging or dropping in IB or writing in code, each uiview had its own frame property to define its position and size in the current view. With AutoLayout, it becomes the use of constraints to define the location and dimensions of the view. The biggest advantage of this is that it solves the problem of view adaptation in different resolutions and screen sizes, and simplifies the definition of the position of the view at the point of rotation, with a view that is centered 10 pixels above the bottom. Whether you're rotating the screen or changing the device (ipad or IPhone5, or the mini ipad that might appear later), it's always centered 10 pixels above the bottom and doesn't change. Summarize
using constraints to describe the layout, the view frame is calculated based on these constraints Describe the layout with constraints, and frames is calculated automatically.
The difference between AutoLayout and autoresizing mask autoresizing Mask is an old friend of ours ... If you've always been a code-writing UI, you've definitely written enumerations such as Uiviewautoresizingflexiblewidth, and if you've used IB a lot before, you must have noticed the size of each view. Inspector has a red line in the autoresizing indicator and the corresponding animation scaled, which is autoresizing Mask. Before IOS6, the adaptation of screen rotation and the automatic adaptation of the Iphone,ipad screen were basically done by autoresizing mask. But with the increasing demands for iOS apps, and the devices that have been and are likely to appear in multiple screens and resolutions in the future, autoresizing mask is a bit outdated and dull. AutoLayout can do all the work that the original autoresizing mask can do, and also be able to perform tasks that were previously impossible, including:
    • AutoLayout can specify the relative position of any two view without needing two view in the immediate view hierarchy like Autoresizing mask.
    • AutoLayout does not have to specify a constraint on an equality relationship, it can specify a non-equality constraint (greater than or less than, etc.), and the layout that autoresizing mask can make can only be of equal condition.
    • The AutoLayout can specify the precedence of the constraint, and the calculation of the frame takes precedence over the condition that satisfies the high priority.
Summarize
Autoresizing Mask is a subset of AutoLayout, and any work that can be done with autoresizing mask can be done with AutoLayout. AutoLayout also has some excellent features that autoresizing mask does not have to help us build the interface more easily.
AutoLayout Basic Use Method Interface Builder This part of the online a lot of tutorials, are said this
To add a constraint manually using the API create a new class in IOS6: Nslayoutconstraint, a constraint that is shaped like this
    • Item1.attribute = multiplier? Item2.attribute + constant
The corresponding code is
1 [NSLayoutConstraint constraintWithItem:button
2                              attribute:NSLayoutAttributeBottom
3                              relatedBy:NSLayoutRelationEqua
4                                 toItem:superview
5                              attribute:NSLayoutAttributeBottom
6                             multiplier:1.0
7                               constant:-padding]
The corresponding constraint is "bottom of button (y) = bottom of Superview-10". Added after you create a constraint, you need to add it to the view that you are acting on. UIView (NSView, of course) added a new instance method:
    • -(void) AddConstraint: (Nslayoutconstraint *) constraint;
Used to add a constraint to a view. The only thing to note when adding a target view is to follow these rules:
    • For a constraint relationship between two levels of view, add 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

Refreshes can be-setneedsupdateconstraints and-layoutifneeded two methods to refresh the constraint changes, so that the UIView re-layout. This is the same thing as Coregraphic's-setneedsdisplay set of things. ~visual format Language Visual Format Language Uikit team This time quite has the love, presumably they also think the new constraint API name is too long, So they invented a new way to describe constraints, which is interesting. This language is an abstraction of the visual description, and the approximate process looks like this: The Accept button is at the default spacing at the right of the Cancel button



Finally, the use of the VFL (Visual Format Language) description becomes:
1 [NSLayoutConstraint constraintsWithVisualFormat:@\\"[cancelButton]-[acceptButton]\"
2                                         options:0
3                                         metrics:nil
4                                           views:viewsDictionary];
Where Viewsdictionary is the dictionary that binds the name and object of the view, for this example the corresponding dictionary can be obtained in the following ways:
1 UIButton *cancelButton = ...
2 UIButton *acceptButton = ...
3 viewsDictionary = NSDictionaryOfVariableBindings(cancelButton,acceptButton);
The generated dictionary is
Of course, not too tired words of their own handwriting is also possible. Now the dictionary, the array, the writing is relatively simplified, so it is not complicated. About Objective-c's new syntax, you can refer to my previous article WWDC 2012 notes: WWDC session notes--405 modern objective-c. Adding parentheses after the view name and the number at the junction can give the expression more meaning, here are some examples:
    • [CancelButton (]-12-[acceptbutton) (50)]
      • Cancel button Width 72point,accept button width 50point, spacing between them 12point
    • [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)]
      • Vertical layout, first a Redbox, below which is immediately below a width equal to Redbox width yellowbox
    • H:|-[find]-[findnext]-[findfield (>=20)]-|
      • Horizontal layout, find the default interval width of the left edge of the parent view, followed by the FindNext distance from the Find interval default width, and then the 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 Superview)
Error prone because of the constraints involved, so all possible problems under the constraint model will appear here, specifically including two kinds:
    • Ambiguous layout cannot be determined
    • Unsatisfiable Constraints cannot meet constraints
Layout cannot be determined to refer to the given constraints cannot uniquely determine a layout, that is, the constraints are insufficient to get unique layout results. This situation generally adds some necessary constraints or adjustment priorities that can be resolved. The problem source that can not satisfy the constraint is that there are constraints conflicting with each other, so it is not possible to satisfy at the same time, some constraints need to be removed. Both errors can cause layout instability and errors when they occur, ambiguous is tolerated and a viable layout is chosen to render on the UI, and unsatisfiable will not be able to get the UI layout and error. For an indeterminate layout, you can pause the program during debugging and enter the debugger in the
    • PO [[UIWindow Keywindow] _autolayouttrace]
To check if there is a ambiguous layout and where it exists to help add conditions. There are also check methods to see the constraints and constraints of the view:
    • [View Constraintsaffectinglayoutfororientation/axis:nslayoutconstraintorientationhorizontal/vertical]
    • [View Hasambiguouslayout]
      • [View Exerciseambiguityinlayout]
Layout animation is an important part of the UI experience, and it is also critical to change the animation after the layout. Speaking of animation, Core animation again meritorious. Since the advent of the CA, all animation effects are very cheap, in the auto layout is also the same as in Collection view, very simple (can refer to WWDC session notes--219 Advanced Collection Views and Building Custom Layouts), only need to put layoutifneeded into the animation block can ~
1 [UIView animateWithDuration:0.5 animations:^{
2     [view layoutIfNeeded];
3 }];
Some code pure code UI Normal layout, add AutoLayout on it, adjustment is quite convenientThis is a horizontally centered, vertically parallel 4 button layout codeSettranslatesautoresizingmaskintoconstraints is for no, turn on autolayou.

-----AutoLayout

[_btn_1 Settranslatesautoresizingmaskintoconstraints:no];

[_btn_2 Settranslatesautoresizingmaskintoconstraints:no];

[_btn_3 Settranslatesautoresizingmaskintoconstraints:no];

[_btn_4 Settranslatesautoresizingmaskintoconstraints:no];

Cgsize winsize = [[Ihappysdksingle sharesingle] getscreensize];

cgfloat tpo = _BTN_1.FRAME.ORIGIN.Y;

CGFloat hpod = _btn_1.frame.origin.x;

CGFloat BTNH = _btn_1.frame.size.height;

CGFloat vpod = WINSIZE.WIDTH*0.15-BTNH;

nsnumber* TP = [NSNumber NUMBERWITHFLOAT:TPO];

nsnumber* HD = [NSNumber numberwithfloat:hpod];

nsnumber* VD = [NSNumber numberwithfloat:vpod];

nsnumber* BH = [NSNumber NUMBERWITHFLOAT:BTNH];

nsnumber* BTM = [NSNumber numberwithfloat:vpod*2];

Nsdictionary *dict1 = nsdictionaryofvariablebindings (_btn_1,_btn_2,_btn_3,_btn_4);

Nsdictionary *metrics [Email protected]{@ "hpadding": hd,@ "vpadding": vd,@ "Top": tp,@ "BTM": btm,@ "btnheight": bh};

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

[Self.view addconstraints:[nslayoutconstraint CONSTRAINTSWITHVISUALFORMAT:VFL1

options:0

Metrics:metrics

Views:dict1]];

NSString *VFL2 = @ "|-hpadding-[_btn_2]-hpadding-|";

[Self.view addconstraints:[nslayoutconstraint CONSTRAINTSWITHVISUALFORMAT:VFL2

options:0

Metrics:metrics

Views:dict1]];

NSString *vfl3 = @ "|-hpadding-[_btn_3]-hpadding-|";

[Self.view addconstraints:[nslayoutconstraint Constraintswithvisualformat:vfl3

options:0

Metrics:metrics

Views:dict1]];

NSString *vfl4 = @ "|-hpadding-[_btn_4]-hpadding-|";

[Self.view addconstraints:[nslayoutconstraint Constraintswithvisualformat:vfl4

options:0

Metrics:metrics

Views:dict1]];

NSString *VFL5 = @ "v:|-(<=top)-[_btn_1 (btnheight)]-vpadding-[_btn_2 (btnheight)]-vpadding-[_btn_3 (btnHeight)]- Vpadding-[_btn_4 (Btnheight)-(>=BTM)-| ";

if (_btn_1.hidden) {

VFL5 = @ "v:|-(<=top)-[_btn_2 (btnheight)]-vpadding-[_btn_3 (btnheight)]-vpadding-[_btn_4 (btnheight)]-(>=BTM) -|";

}

[Self.view addconstraints:[nslayoutconstraint CONSTRAINTSWITHVISUALFORMAT:VFL5

options:0

Metrics:metrics

Views:dict1]];

After the clean code UI is properly laid out, add a function for automatic layoutHorizontal Center layout:NslayoutattributecenterxVertical Center layout:Nslayoutattributecenteryand the subsequent layout toggle animations.

-(void) Setautolayoutforkuang: (uiview*) IMGV

{

UIView * view = self;

[IMGV Settranslatesautoresizingmaskintoconstraints:no];

Nsdictionary *dict1 = nsdictionaryofvariablebindings (IMGV);

Nsdictionary *metrics = @{@ "width": [NSNumbernumberWithFloat:imgv.frame.size.width],

@ "height": [NSNumber NumberWithFloat:imgv.frame.size.height],

@ "Top": [NSNumber NUMBERWITHFLOAT:IMGV.FRAME.ORIGIN.Y]

};

NSString *VFL1 = @ "[IMGV (width)]";

[View Addconstraints:[nslayoutconstraint CONSTRAINTSWITHVISUALFORMAT:VFL1

options:0

Metrics:metrics

Views:dict1]];

NSString *VFL2 = @ "V:[IMGV (height)]";

[View Addconstraints:[nslayoutconstraint CONSTRAINTSWITHVISUALFORMAT:VFL2

options:0

Metrics:metrics

Views:dict1]];

[View Addconstraint:[nslayoutconstraint ConstraintWithItem:imgvattribute:NSLayoutAttributeCenterX Relatedby: Nslayoutrelationequal ToItem:viewattribute:NSLayoutAttributeCenterX multiplier:1 constant:0];

[View Addconstraint:[nslayoutconstraint ConstraintWithItem:imgvattribute:NSLayoutAttributeCenterY Relatedby: Nslayoutrelationequal ToItem:viewattribute:NSLayoutAttributeCenterY multiplier:1 constant:0];

Animation

[UIView animatewithduration:0.25 animations:^{

[IMGV layoutifneeded];

}];

}

-----------------------------------------Online related articles:-----------------------------------------1, AutoLayout (Automatic layout) get started Recommended 2, AutoLayout and the VFL experience sharing this article contains a demo (Quick access Download) Recommendation 3, IOS 6 Auto layout Nslayoutconstraint interface layout Not a friend worrying about manually these script-like characters: Now recommend an open source Library for everyone Github:https://github.com/telenliu/lyt[email protected]: Http://git.oschina.net/TelenLiu/Lyt

iOS Development multi-screen ruler automatic adaptation AutoLayout (pure code mode)

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.