Automatic UI Layout

Source: Internet
Author: User

Automatic UI Layout

When the internal or external conditions change, the position and size of the view are automatically recalculated.

For ios apps, changes that can trigger automatic layout can be divided into external changes and internal changes:
External changes can be the orientation of the device, the split screen of the ipad, and screens of different sizes.
Internal changes can be content changes (loading different images, etc.), applications support dynamic types (allowing users to modify views), and internationalization (adding support for multinational users.

The relationship between ios's Automatic Layout and frame-based layout is like the relationship between Android's relative layout and absolute layout. The frame-based layout refers to the absolute position and absolute size of the Child view relative to the coordinates of the parent view. The advantage of this layout is that the coordinates are determined, but in the face of a variety of screen sizes, dynamic Content and other issues are very troublesome. Different automatic la s describe the positional relationship between views. No matter how the screen size or content changes, the relative positions between views remain unchanged, and the view layout will not be lost.

The automatic layout must be implemented by the constraints constraint. The following describes how to use constraints to implement automatic layout, and how to create, modify, and view constraints.

I. Use the Constraint for Automatic Layout (the principle of automatic layout)

The layout is actually a series of equations about the view position. Each equation is a constraint. A constraint generally describes the numerical relationship between two attributes, such as the number of times the length is width, and the starting position of view2 is the count position of view1 plus 10.

The equation in the figure is a typical constraint. The object to be bound is the Attribute1 attribute of RedView (item1). The specific content of the constraint is that the trailing attribute (Attribute2) of BlueView (item2) is multiplied by 1.0 plus 8.0. This 1.0 is called the product factor multiplier and 8.0 is a constant. The meaning of these quantities must be clear, because these quantities are inseparable from the constraints created later.

1. common attributes of Automatic Layout (there are also several common attributes)

Four boundaries of a view: leading (left boundary), trailing (right boundary), top (upper boundary), and bottom (bottom boundary)
View Size: height (height), width (width)
Center of the View: center (center Coordinate)

2. Principles of Automatic Layout

First, the attributes of automatic layout can be divided into location-related attributes and size-related attributes. There should be no association between these two attributes. The following principles must be observed:
Do not use the location attribute to constrain the size attribute.
Do not assign a constant value to the location property.
The product factor must be 1.0 in the constraints of location attributes.
Do not use the location attribute in the horizontal direction to constrain the location attribute in the vertical direction.
Do not use the leading or trailing attribute to constrain the left or right attributes.

3. the constraint of Automatic Layout is indeed an equation, not a value assignment statement.

For constraints that exist in the form of equations, instead of assigning the value on the right of the equal sign to the value on the left of the equal sign, the equation is solved to make the equal signs on both sides equal.
Therefore, when the equation has multiple solutions, that is to say, there may be multiple layout solutions that can satisfy these constraints, we need to determine a solution from it and continue to use it. For example, the product factor of an integer takes precedence over the decimal product factor, the positive product factor takes precedence over the negative number, and the views are arranged from top to bottom, from left to right. These rules need to be set by yourself and are always observed in a project.

4. Create a definite Layout

The purpose of Automatic Layout is to generate a set of definite la s, that is to say, there are as few la s as possible to satisfy all constraints. Just like determining a straight line at two points, you need to create a definite layout and its rule: the two attributes determine the location of one dimension of a view.
If you determine the position of a view in the horizontal direction (three methods, corresponding to left, center, right)
Method 1: restrict the distance between the left boundary and the parent view and the width of the view.
Method 2: simultaneously constrain the distance between the left and right borders and the parent View
Method 3: constrain the distance between the left boundary and the parent view and the central position of the view.

Analysis of the above three methods:
Method 1: The disadvantage is that the view width cannot change with the size of the parent view.
Method 2: the distance between the left and right borders and the parent view is fixed (the two distances can be different)
Method 3: This method is most convenient when many center-aligned views need to be placed.

5. Inequality

In the constrained equation, except equal sign =, greater than sign>, less than sign <, greater than or equal to> =, and less than or equal to sign <=.
The inequality restricts the range of attributes. You can use equality constraints and Inequality Constraints to determine the layout.

6. constraint priority

By default, the automatic layout will calculate a layout scheme that meets all constraints. If it cannot be calculated, the unsupported constraints will be output in the console, and select one of them, do not observe, and then re-calculate.
You can create an optional constraint by determining the priority of the constraint. The priority range is 1-1000. The constraint with a priority of 1000 must be met, and others are optional. The Automatic Layout calculates the layout scheme in the order of priority. If it does not meet the optional constraints, it will be skipped. If you skip a constraint and the layout becomes uncertain (there are multiple solutions), the layout will select the value closest to the constraint to determine the layout.

7. Default size

Some controls have the default size. For example, common scyclers have the default width, while label, button, switch, and textField have the default width and height.
Generally, the default size of these controls is based on its content. Just as after the image is set in imageView, the default size is the image size. The default size of imageView and textView is affected by content, whether to allow scrolling, and other constraints.
IOS officially recommends that you use the default size of the view as much as possible, because it allows the view to automatically adjust the size to adapt to changes in its content, or reduce the number of constraints to be specified.
When using a view of the default size, two size-related constraints are usually combined. One is "Preventing being stretched" and the other is "Preventing being compressed ", this document calls it CHCR (Content-Hugging and Compression-Resistance ). The focus of using these two constraints is to adjust the relative priority of the CHCR between views. For example, there are two views at the same horizontal height, both of which use the default size. When you need to stretch these two views (both smaller) to fill the width of the parent view, the priorities of the two views in the horizontal direction are compared to those of the "prevent being stretched" constraint. If the priority of the two views is small, the corresponding views will be stretched, the other view maintains the default size. If the two priorities are equal, the automatic layout mechanism does not know which view to stretch.
Generally, unexpected results are displayed in the view layout with the default size, which may be stretched in many cases. To avoid this situation and prevent the control from being stretched, you can set a higher priority for the Content-Hugging constraint.
Baseline constraints only apply to views that maintain the default height.

8. Available references

Some attributes can be used as references when writing constraints (item2 In the constraint equation:

(1) top layout guide and bottom layout guide on the top and bottom navigation bars of the Root View of the View Controller. Since iOS 7.0, the UIViewController class has two attributes: topLayoutGuide and bottomLayoutGuide.

The top navigation bar and the bottom navigation bar I mentioned here are not narrow navigationBar and tabBar, but general components that are blocked at the top and bottom of the current Root view (such as the navigation bar ). Specifically, when statusBar and translucent navigationBar are visible, topLayoutGuide is the part of the status bar and navigation bar. When navigationBar is invisible, topLayoutGuide is the status bar, if the status bar is hidden, there will be no topLayoutGuide. For bottomLayoutGuide, when tabBarController. tabBar or toolBar is visible, bottomLayoutGuide is the tabBar or toolBar part, and when the tabBar is invisible, bottomLayoutGuide is gone.
These two attributes also follow a protocol, UILayoutSupport protocol. This Protocol defines four attributes: length, bottomAnchor, heightAnchor, and topAnchor.
What is length? For topLayoutGuide, It is the bottom boundary of topLayoutGuide; For bottomLayoutGuide, It is the upper boundary of bottomLayoutGuide.
If you directly access viewController. topLayoutGuide in the code, viewController. topLayoutGuide. length is returned. If you access bottomLayoutGuide, bottomLayoutGuide. length is returned. Therefore, in the Code, topLayoutGuide and bottomLayoutGuide can be understood as the upper and lower boundary of the visible area of viewController. view.
However, in the visualized autoLayout, the two are understood as the section where viewController. view is blocked up and down.
BottomAnchor, heightAnchor, and topAnchor are used to implement autoLayout in code implementation.

(2) padding and inner boundary-margins and margins guides

The padding is the minimum distance between the view boundary and the sub-view.
UIViewController has two attributes related to the padding. One is layoutMargins and the other is layoutMarginsGuide. LayoutMargins is the size of the padding. LayoutMarginsGuide refers to the inner boundary.
When writing constraints, they are usually relative to the inner boundary. The default padding size is 8 points.

(3) text boundary -- readable Content Guides

UIViewController has a property readableContentGuide related to the text boundary. It refers to the boundary of the largest area that can be displayed by text. Normally, this boundary is not much different from the inner boundary. It is obvious only when the pad is landscape. If necessary, you can choose to compare the layout with the text boundary instead of the inner boundary.

Ii. constraint management (the practical part of automatic layout, adding, deleting, modifying, and querying constraints)

The management of constraints can be implemented through visual Interface Builder or code. This section describes how to manage constraints in InterfaceBuilder. The next section describes how to implement the Code.
The implementation method is to directly drag the view and SET related constraints in the interface Builder on the right side of xcode. In fact, constraints can be implemented using code. Not mentioned in this section. Next section.
For those who previously used code to create a view, it is necessary to first know how to create and associate xib. If you already have this section, skip it.
(1) Method 1: Create a ViewController and xib. Like creating a new ViewController, Also create XIB file is checked. In this way, an xib is automatically created and associated with the created ViewController.

(2) Method 2: Create xib by yourself and associate it with the existing ViewController.
Use new File to create xib. To associate xib with the existing ViewController, you only need one step.
Open xib, find this icon on the left, click it, find the tab on the right, click the third one, and then you will see the Custom Class below, select the ViewController to be associated in the Class column.

Note: you need to set the xib Root view by holding down Ctrl and clicking the file's Owner above to drag it to the view. You can.
Note: When creating ViewController, do not directly [[ViewController alloc] init]. Instead, use initWithNibName: bundle: Method for initialization, specify the xib file as your Root View.

Return to the topic and use constraints to achieve automatic layout:

1. Two Methods for creating constraints (1) Method 1:

Press and hold control + and click item1 and drag it to item2 to create a constraint () for an attribute of item1 on an attribute of item2 ().

(2) Method 2: four tools for quickly generating constraints (at the bottom of xcode, this method is The most convenient and commonly used):


The first tool is to quickly create stackView.
The second tool can quickly create constraints on view alignment.
The third tool can quickly establish constraints on the width, height, length and width ratio of views, and the distance between views and adjacent views.
The fourth tool can automatically generate constraints, clear constraints, and update view la S.
Notes for using these four tools:
To use these tools, you must first click the view to be constrained, and then click a tool.
For the first tool, you must first select the view that needs to be added to stackView, and then click the first tool.
Select multiple views. You can press shift to select the view to be selected one by one. You can also press the Alt key to select the view to be selected in a one-time box.
Note that the second tool is about alignment. To set the alignment relationship between a view and the root view, select the view and click the second tool. If you want to set the relationship between multiple views, You need to select these views at the same time, and then click the second tool to set them.

Is to set the relationship between a view and its parent view. The selected items are valid and those not checked are invalid. Horizontally in iner is the amount of Horizontal Deviation from the horizontal position of the parent View Center. It is a negative value to the left and a positive value to the right. Vertically in iner is vertical.
In the third tool, there is a constrain to margins where the distance between the management view and the adjacent view is located. If this option is selected, the values are relative to the inner boundary. If this option is not selected, it is relative to the border (edge) of the Root View ).

Also, the values on the left and above take effect, while those on the right and below do not. That is to say, whether or not the actual situation of the line is determined to take effect.
The fourth tool is divided into two columns: selected Views and All Views in View Controller. The former indicates that the operation object is the selected View, the latter indicates that the operation object is all views in the View Controller. Update Frame is the frame of the view updated according to the existing constraints. Update Constraints updates Constraints based on the current view layout.

2. view the constraints in three methods:

(1) Method 1: Left side of xcode

(2) Method 2: view the constraints of a view. Click the view first, and then click the fifth icon on the Right of xcode to view all the constraints () on The View ().

(3) method 3: Use small labels or lines:
Select the view to be viewed, And then you can see small labels and lines (representing constraints) around it. Click them to view the corresponding constraints on the right.

The color of labels and cables makes sense:
Green usually indicates that the constraints on this view can uniquely determine the layout of this view.
Red indicates that the layout of the view cannot be uniquely determined, or the constraint conflict.
Orange indicates that the constraint determines the position of the view relative to the root view.

3. Edit Constraints

(1) view the constraint by the first or third method of the view constraint, and click the constraint to be edited. Click the fourth or fifth icon on the right side of xcode to view the editing area of the constraint.

(2) view constraints in the second method of view constraints. Click the edit button next to the constraint to edit the constraint.

4. Apple officially provided some suggestions on automatic layout.

These suggestions are applicable no matter whether you use interfaceBuilder or code to implement automatic layout.
(1) You do not need to specify the view shape using the frame, bounds, and center of the view.
(2) Try to use stackView for Layout
(3) constraints should be established between the view and its adjacent view.
(4) Avoid specifying a fixed length and width for the view.
(5) Pay attention to automatically update the view frame, especially for views with insufficient constraints.
(6) The names of views should be meaningful, so that they can be recognized during layout.
(7) use leading and trailing constraints. Do not use left or right.
(8) When writing Constraints Relative to the view boundary, there are two situations:
Horizontal constraint: For most controls, the constraint should be relative to the internal boundary of the Root View.
When text like a novel reader is full of screens, the constraints should be relative to the text boundary.
For a view whose width needs to be filled with the Root View, the constraint can be relative to the border of the Root View.
Vertical constraints: If the root view is partially blocked by the navigation bar, tabBar, and so on, the constraints should be relative to top margin and bottom margin.
(9) When using autolayout to deploy the views created using code, set their translatesAutoresizingMaskIntoConstraints attribute to NO. If this attribute is set to YES, the system automatically generates some constraints for these views. These constraints may conflict with the constraints we set.

3. Use code to create constraints

There are three ways to create constraints using code: Use the NSLayoutConstraint class, use the layout anchor (anchor), and use the Visual Format Language.

1. method 1 (old method): Use the NSLayoutConstraint class

In the constraints principle, the form of the constraint equation is as follows: item1.attribute1 = multiplier × item2.attribute2 + constant. It consists of seven parts: item1, attribute1, item2, attribute2, relationship, multiplier, and constant. The function of the NSLayoutConstraint class is to construct a constrained equation using seven quantities of constrained equations and let them be true. The example above is the most intuitive:

NSLayoutConstraint(item: myView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .LeadingMargin, multiplier: 1.0, constant: 0.0).active = true

As mentioned above, a constraint is created: myView. leading = view. leadingMargin × 1. 0 + 0.0.
This method is an old method to create constraints. Apple officially recommends that you use anchor to create constraints for the new method that appears after iOS 9.0.

2. Method 2: Use anchor

The principle of using anchor is essentially the same as that of using the NSLayoutConstraint class, but the expression is more concise.
For details, see the NSLayoutAnchor class.

3. Use Visual Format Language

Directly read the official website documentation Visual Format Language, which is so intuitive.

Summary

Currently, autoLayout is the most convenient tool provided by interface Builder. These four tools can create multiple constraints at a time and write them one by one using code.

Another way of Automatic Layout is to use stackView to dynamically increase or decrease the view.

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.