AutoLayout Automatic Layout

Source: Internet
Author: User

 AutoLayout Automatic Layout Getting Started with AutoLayout (auto layout)

This is one of the bloggers ' WWDC2012 notes, and the complete list of notes can be see here. If you are on this site for the first time, you may be interested in subscribing to this site via RSS or by subscribing to the email on the left side of the page.

AutoLayout was introduced to cocoa in WWDC last year, and on this year's WWDC, Apple spent three sessions to explain to developers in detail the AutoLayout app on iOS, The reason: IPhone5 's screen will turn 4 inches, and developers will soon be faced with the job of adapting to different screen sizes. The worst-fit job of Android platform development now seems to be on the head of iOS developers. Based on this situation, Apple is aggressively promoting the use of the AutoLayout approach to UI layout to eliminate the hassle of adaptation at a stroke. AutoLayout will be another important change in UI production since Interface Builder and storyboard, and it must be the trend behind iOS development, so this topic is worth learning.

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

The simplest way to use it is to drag it directly in IB. Under the file inspector of any of the view in IB, there is the Use AutoLayout selection box (no classmates can consider upgrading Xcode =. =), hook up, and then drag the control as you normally would. Drag the control to the left of the view hierarchy bar will appear constraints always, which is all the constraints.

When a constraint is selected, you can change the condition, distance value, and priority of the constraint in Attributes Inspector on the right:

For constraints that are not automatically added, you can add them manually in IB. Select the view you want to add a constraint to, click the option you want in the Edit->pin of the menu, or click the button in the lower right corner of the IB view to add extra constraints.

Visual addition is not only convenient and intuitive, but also basic error-prone, is the preferred way to add constraints. However, sometimes only IB is unable to complete the addition of certain constraints (such as cross-view hierarchy constraints), sometimes the constraints added by IB do not meet the requirements, it is necessary to use the constraints of the API to supplement.

Manually using the API to add constraint creation

A new class has been added to the iOS6: Nslayoutconstraint, a constraint that is shaped like this

    • Item1.attribute = multiplier? Item2.attribute + constant

The corresponding code is

[NSLayoutConstraint constraintWithItem:button                             attribute:NSLayoutAttributeBottom                             relatedBy:NSLayoutRelationEqual                                toItem:superview                             attribute:NSLayoutAttributeBottom                            multiplier:1.0                              constant:-padding]

The corresponding constraint is "bottom of button (y) = bottom of Superview-10".

Add to

After you create a constraint, you need to add it to the action view. 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

* 对于两个不同层级view之间的约束关系,添加到他们最近的共同父view上

* 对于有层次关系的两个view之间的约束关系,添加到层次较高的父view上

Refresh

Changes to the constraint can be refreshed by-setneedsupdateconstraints and-layoutifneeded two methods to make the UIView re-layout. This is the same thing as Coregraphic's-setneedsdisplay set of things.

Visual format Language visual formatting language

The Uikit team had a lot of love this time, and presumably they themselves felt that the new constraint API name was too long, so they invented a new way to describe the 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:

[NSLayoutConstraint constraintsWithVisualFormat:@"[cancelButton]-[acceptButton]"                                         options:0                                         metrics:nil                                           views:viewsDictionary];</pre>

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:

UIButton *cancelButton = ...  UIButton *acceptButton = ...  viewsDictionary = NSDictionaryOfVariableBindings(cancelButton,acceptButton);  

The generated dictionary is

{ acceptButton = ""; cancelButton = ""; }

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)
Errors that occur easily

Because of the constraints involved, all the 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]

September 1, 2013 author update: In IOS7 and Xcode5, IB has made great strides in adding and checking autolayout constraints. It is now easier to use IB to complete complex constraints, and thanks to the new IB's constraint checking mechanism, we seldom meet with missing or redundant constraints (the problematic constraints will get errors or warnings directly from IB). However, it may be necessary to add code to the fact that it is possible to use IB to achieve the constraints that are really wonderful.

Layout animations

Animations are an important part of the UI experience, and it is critical that you 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 ~

[UIView animateWithDuration:0.5 animations:^{    [view layoutIfNeeded];}];

AutoLayout Automatic Layout

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.