Swift language auto layout Getting Started Tutorial: Previous
Start thinking in the form of automatic layout constraints!
Update record: This tutorial was updated by Brad Johnson for Swift and iOS 8, with the first version of the author being the Matthijs Hollemans of the tutorial compilation group.
Have you ever been bothered by the app's ability to display a neat interface in both portrait and landscape mode? Have you ever been upset about the layout supporting both the iphone and the ipad? Don't lose heart, the good news is coming!
Designing a user interface for an exact size screen is not a hassle, but if the frame of the screen is not fixed, the location and size of each UI element in the app needs to be adjusted to fit the new environment.
The evolution of auto layout is commendable. Xcode 4 introduces auto-layout for the first time, and if you do, you really should give Xcode 61 more chances now. Xcode 5 and iOS 7 have dramatically optimized auto-layout capabilities, and now with two different sizes of big-screen new iphone releases, Xcode 6 and iOS 8 continue to make improvements. Automatic layout has become an essential tool for every iOS developer.
The automatic layout not only simplifies the work of adapting different screen sizes, but also eliminates the hassle of internationalization (internationalization), and never creates a new nib or storyboard for the languages you want to support. These include right-to-left languages such as Hebrew and Arabic.
Have a cup of coffee to cheer up, to pack spicy pressure yajing, ready to start automatic layout Master's spiritual journey!
The question of "spring support Rod"
Open Xcode 6 and create a new iphone Swift project based on the single view application template, named "Strutsproblem":
You may be familiar with autosizing mask (auto-scaling mask), the so-called "spring support rod (springs and struts)" model. When the parent view size of a view changes, the auto-scale mask determines how it makes adjustments. Where the "Support bar" is the margin (margin) is fixed or variable, and "Spring" is how its width and height adjustment.
For example, if the elastic width is applied, the child view is scaled proportionally when the parent view becomes wider, and if a fixed right margin is used, the right edge of the child view remains relatively fixed with the right edge of the parent view.
In general, the automatic scaling mechanism can be completely satisfied with simple requirements, but for complex layout problems. Let's take another example, in which case the "Spring Support bar" model is powerless:
Click Main.storyboard to open in Interface Builder, disable auto layout and size Classes (size collation) in this storyboard before proceeding. Both of these options are in the file inspector, the first of the six tags.
Deselecting the use Auto layout will also tell you that the dimension collation is not available, it's OK, storyboard will switch to the previous spring support bar model after confirmation.
Note: Automatic layout is activated by default for any nib or storyboard file that you create with Xcode 4.5 or later. Since auto layout is a feature introduced from iOS 6, if you want to build an iOS 5-compatible app with the latest Xcode, you'll need to deselect "use Auto layout" in all the new nib and storyboard to disable automatic layouts. The dimensions are categorized as compatible with iOS 7 and newer systems.
Drag three views into the main view and arrange:
For easy identification, set different colors for each view.
Each view is embedded (inset) in the window (Windows), 20 points from the edge. The spacing between views is also 20 points. The bottom view has a width of 280 points, and the top two views are 130 points wide. All view heights are 254 points.
If you don't want to drag and drop, you can also open the dimension Inspector (Size inspector) to set the following property values with keyboard input:
-
Top Left: Origin 20,20, Size x 254
-
Top Right: Origin 170,20, Size x 254
-
Bottom: Origin 20,294, Size 280 x 254
With the new feature, preview Assistant, you don't have to run the app to see what the layout actually looks like. Open the Auxiliary editor (Assistant Editor), and select Preview/main Storyboard in the selection bar at the top of the secondary editor (which typically displays "Automatic"):
In the preview assistant, you can add as many analog devices as you like, is it more convenient than building separately on different device emulators? Click the + button in the lower left corner to add the device, configure two 4-inch iphone screens, and rotate one of them to landscape mode with the button next to the device name.
The app doesn't look right in landscape mode:
In fact, the horizontal screen you want is this:
Obviously, the auto-scaling masks for three views do not fully meet the requirements. To modify the Autoscale settings for the upper-left view:
This causes the view to snap to the top and left edges (without snapping to the bottom and right edges) and scale vertically when the parent view changes size.
Similarly, modify the Autoscale settings for the upper-right view:
There are also the following views:
You'll see a change in the layout in the preview assistant, which is probably the case now:
It's not much, but it's almost there. The view spacing is incorrect, or the location of the view is roughly correct, but the size is problematic. The problem is that when the parent view size changes, the Autoscale mask simply notifies the child view to resize, but cannot tell how much the child view should be adjusted.
You can continue experimenting with auto-scaling masks, for example, modifying the elastic width-height setting ("Spring"), but not all of the results we expect (20 points apart per view).
Unfortunately, in the "Spring support bar" mechanism to solve such layout problems can only write code.
Before, during, and after the user interface is rotated, Uikit sends several messages to your view controller, which you can use to complete the layout adjustment of the user interface. The usual practice is to rewrite the viewwilllayoutsubviews and modify the view frame that needs to be restructured.
Before overriding the method, you must also create a outlet property that points to the view that needs to be restructured.
Click the button in the middle of the Editor tool Group on the Xcode toolbar to switch to the secondary editor mode, and then control-drag the corresponding three views to Viewcontroller.swift:
Connect the corresponding view to these three properties individually:
@IBOutlet weak var topLeftView: UIView!
@IBOutlet weak var topRightView: UIView!
@IBOutlet weak var bottomView: UIView!
Add the following code to the Viewcontroller.swift:
override func viewWillLayoutSubviews() {
if UIInterfaceOrientationIsLandscape(self.interfaceOrientation) {
var rect = self.topLeftView.frame
rect.size.width = 254
rect.size.height = 130
self.topLeftView.frame = rect
rect = self.topRightView.frame
rect.origin.x = 294
rect.size.width = 254
rect.size.height = 130
self.topRightView.frame = rect
rect = self.bottomView.frame
rect.origin.y = 170
rect.size.width = 528
rect.size.height = 130
self.bottomView.frame = rect
}
else {
var rect = self.topLeftView.frame
rect.size.width = 130
rect.size.height = 254
self.topLeftView.frame = rect
rect = self.topRightView.frame
rect.origin.x = 170
rect.size.width = 130
rect.size.height = 254
self.topRightView.frame = rect
rect = self.bottomView.frame
rect.origin.y = 295
rect.size.width = 280
rect.size.height = 254
self.bottomView.frame = rect
}
}
This callback method is triggered when the view controller is rotated to the new orientation mode, checks the direction the view controller is rotated and adjusts the view size appropriately, in this case a fixed parameter corresponding to the known iphone screen specification. The callback method is carried out in an animated block, so the resizing process has an animated effect.
Do not run now, you also need to reset the Autoscale mask settings for three views, otherwise the Autoscale mechanism will conflict with the location and size set in the Viewwilllayoutsubviews method:
It should be all right now. Run the app on the iphone 5 simulator (the code won't take effect in the Preview assistant!) ), switch to landscape mode. Now the view layout is structured, cut back to portrait mode and check that the display is normal.
It does, but this simple layout problem requires writing dozens of lines of code, for complex layout problems, in particular, each individual view will change the size, or the number of sub-views of the dynamic situation, the code how Fanluan, Imagine.
Try this back on the 3.5-inch simulator. Worse, the location and size of the view is problematic because the coordinate data previously encoded in Viewwilllayoutsubviews is based on the 4-inch iphone screen specification (320x568 instead of 320x480, in points). You can add an if statement to determine the screen size, and then write a different set of coordinate data, but you understand that this method is becoming more and more unreliable.
Another workaround is to create a different nib for both the vertical and horizontal screens. When the device rotates, load from another nib and replace the current view. However, the workload of this program is also very large, and the introduction of two nib is not conducive to post-maintenance, if the use of storyboard instead of NIB, the scheme is more unrealistic.
Automatic Layout to rescue!
You will soon see how to use automatic layout to achieve the same effect. First delete viewwilllayoutsubviewsfrom viewcontroller.swift , the next work line of code also do not write!
Choose Main.storyboard, and then select the use Auto Layout and use Size Classes option in the File Inspector panel. Turn on automatic layout and dimension collation for current storyboard:
What is a size collation
In this translation, when talking about functional features, size classes translates to "Dimension collation", while talking about a specific size class in the actual application scenario, translated to "dimension classes". )
Dimension collation (size Classes) is a great new feature for iOS 8 and Xcode 6. With an intuitive size collation, just one storyboard can take a universal app (Universal app). Almost anything visible on the screen can have a size class, including a screen (UIScreen), a view, and a view controller. There are two major types of dimension classes: vertical and horizontal. The values for each vertical or horizontal dimension class can be one of the general (Regular), condensed (compact), arbitrary (any) three.
The combination of dimension classes corresponds to the device that the app runs and its orientation environment. For example, a vertical iphone corresponds to a normal height and a condensed width. "Any" is a generic dimension class, you can think of it as the parent of all other layouts, and if there is no definition in the dimension class for the current device and direction, storyboard will be laid out according to the configuration in "any".
It is easy to view and toggle the dimension class configuration in Xcode 6. At the bottom of the storyboard panel is a text label that displays "W_any_h_any_", and you can see the dimension class configuration grid by clicking on it:
You can move the mouse pointer between the other blocks in the grid to see what size classes they correspond to. The default state is any width, any height, that is, the generic dimension class configuration. Apple recommends that you do all the initial interface layouts for the generic app in this size class, because all of the dimension classes are based on the generic size class. Make sure that the dimension class selected in the current storyboard is w_any_h_any.
You will notice that the scene in the storyboard becomes a square, reflecting our generic size class configuration.
This tutorial includes only the basics of automatic layout, and for more details on sizing, see our Getting Started with adaptive layouts Tutorial.
Your first auto-layout constraint
Look at the horizontal screen layout in the Preview assistant, which is probably the case now:
Next we'll put the automatic layout into practice. Press and hold the command key and click on the two views above (green and yellow), and select Pin/widths equally (fixed/same width) in the editor directory of Xcode:
Select both views again and select editor/pin/horizontal Spacing(Editor/fixed/horizontal interval). (Although two views still appear to be selected after the first fixed operation, this is a special layout-relationship display mode, so it is necessary to re-select the corresponding view.) )
Now the storyboard shape is as follows:
The orange "beam of work" represents the constraint (constraint) between views. To date, two constraints have been added to the two views, one is the equal width constraint for both (Equal Widths, represented by the equal sign icon), and one is the horizontal spacing constraint between the two (horizontal Space). Constraints can express spatial relationships between views and are the primary tool for building layouts using automatic layouts. A variety of constraints at first glance may be a bit scary, but as long as you understand the meaning, the constraints are very easy to understand.
Follow these steps to continue building the layout, with orange constraints added to each step, and be sure to re-select the view after you add each constraint.
For the green view on the top left, select from the Editor/pin directory:
For the yellow view on the right, select:
There is also the following blue view:
-
Leading space to Superview (header interval with parent view)
-
Trailing space to Superview (trailing interval from parent view)
-
Bottom space to Superview (the bottom interval from the parent view)
(Note: Leading (first)/trailing (tail) and left (right)/right The main difference is that left/right refers to absolute around, and in order to facilitate the internationalization of the interface, leading/ The actual direction of the trailing concept is related to the language's direction of writing, for example, in general, some UI elements that fit in Arabic are also arranged from right to left in the horizontal direction, so in our opinion, some of the Arabic interfaces appear to be inverted around. )
You should now have the following constraints:
Note that some constraints remain orange, meaning that layout settings are not exhaustive, and that automatic layout requires more constraints to calculate the view position and size. The solution is to continue to reasonably add the constraint until all the constraints are blue.
Press the command key to select the three views and select Pin/heights equally (fixed/same height) in the editor menu.
Now similar to the previous, press and hold command to select the upper-left corner and the following view, select Editor/pin/vertical Spacing (editor/fixed/vertical interval).
Interface Builder Display
The restraints are blue, big success! The information provided is sufficient to allow the automatic layout to calculate a valid layout scheme, but there is a problem that there is a large space on the right side of the page when switching to a generic dimension class. Now select the view below and select the Trailing interval constraint:
Open the Dimension inspector and modify the constant (constant) value to 20:
Make the same settings for the view on the right.
Watch the preview layout, look! The vertical screen is great, and all-in-all sizes, 3.5-inch, 4-inch, 4.7-inch, 5.5-inch screens are okay. Add a few devices to the preview assistant to see it. You may now notice that the ipad is also optional and add it, and you'll find that every device can be done with a single layout!
Cool! But what is it that has just been done? The automatic layout lets you describe how the views in the layout form a spatial relationship with other views or the parent view, rather than writing the size and location coordinates of the view yourself in code.
You have added the following relationships to the layout: constraints.
-
The view on the left is consistent with the width of the view on the right. (That is, the fixed same width command begins.) )
-
There is a 20-point horizontal gap between the upper-left view and the top-right view. (that is, fixed horizontal interval.) )
-
All view heights are consistent. (That is, fix the same height.) )
-
There is a vertical gap of 20 points between the two views above and the view below. (that is, fixed vertical spacing.) )
-
There is a 20-point gap between the view and the edge of the screen. (That is, the top, bottom, header, and trailing intervals of the parent view.) )
These constraints are sufficient to convey the location characteristics of the view to the automatic layout, as well as the behavior when the screen size changes.
You can see all the constraints in document Outline on the left, and Xcode adds the constraints (constrain) section to storyboard when auto-layout is enabled. If the outline panel is not visible, click the arrow button below the Interface Builder window.
Click on a constraint in the document outline, and Interface Builder will highlight the position of the constraint in the view with white edges and shadows:
A constraint is a actually existing ' Nslayoutconstraint ' object and also contains related properties. For example, select the constraint that creates an interval between the two views above (named "Horizontal Space (20)", make sure you select it correctly), and then edit the constant field value in the property inspector to modify the spacing.
Set to 100 to see the changes in the preview assistant, the spacing is now significantly increased:
When describing the spatial characteristics of a view in an app, the automatic layout is much stronger than the spring support bar model. This tutorial will then take you through the various constraints and how to apply constraints to build different layouts.
How Automatic Layout works
As you can see above, the basic tools for automatic layout are constraints. A constraint can describe the relations between two views. For example, there are the following constraints:
The distance between the right edge of Label A and the left edge of Button B is 20 points. ”
Automatic layout takes all constraints into account and calculates the ideal position and size of each view in a mathematical way. You no longer have to set the border of the view yourself, and the automatic layout will do it entirely with the constraints you set on the view.
Previously, developers could only write the frame of the view, either set specific coordinates in interface builder or pass a rectangle to the ' init ' method, or set the view's Frame,bounds or center properties directly.
For example, in the app you just built, you need to specify the view frame as follows:
Also set the auto-scale mask for each view:
Now we don't have to think about it any more. With automatic layout, you only need to set:
Today, the exact size and position of the view are no longer important. Of course, when you drag a new control into the panel, you still have the exact size and position, but the main role now is to assist the design, which prompts interface builder where to set the constraint.
The basic idea of automatic layout simplification is to automatically build the remaining layouts in a relative way based on some of the necessary constants set by the developer, such as 20-point spacing, or the exact width of a picture view.
Intent-oriented design
One of the great benefits of using constraints is that you no longer have to toss the coordinate values back and forth in order to display the view in the right place. Now you can describe the relationship of the view to the automatic layout, and then the automatic layout will take care of everything for you. This is "intent-oriented design".
When it comes to intent-oriented design, you express what you want to achieve, without having to describe how. As you might have described earlier, "the coordinates of the upper left corner of this button are at (20, 230)" And now you are saying:
This button is centered vertically relative to the parent view and retains a fixed distance from the left edge of the parent view. ”
Automatic layout automatically calculates where the button should appear, regardless of the parent view size, as described.
To give some examples of intent-oriented design, this type of instruction can be perfectly solved by automatic layout:
The size of the two text fields should be consistent. ”
The two buttons should be moved at the same time. ”
"These four text labels should be right-aligned. ”
As a result, the user interface design is much more descriptive. Simply define the constraints and the system will automatically calculate the frame for you.
As you can see in the first section, it will take a considerable amount of effort to build a simple layout with just a few views, even before it is reasonable. Automatic layout can save time and energy effectively. As long as the constraints are properly set, the layout scheme can properly fit the screen without any modification.
Another important benefit of using automatic layout is internationalization. German, for example, is famous for its long-smelling compound words (such as ballpoint pen kugelschreiber, privacy settings Datenschutzeinstellungen, vernal equinox Frühjahrstagundnachtgleiche), It's so painful to cram this lump into a text label, and now it's easy, auto-layout automatically resizes the content as needed to fit the constraint.
Now the main task of adding support for other languages such as German, French, and so on is to set constraints, translate text, and that's it!
Automatic layout is not only effective for equipment rotation, but also easy to retractable interface, adapt to different screen size. This technology is not a coincidence when it comes to iphone 5 with a longer screen, and now we have bigger iphones 6 and 6 Plus!
With auto-layout, it's easy to expand the user interface on a big screen phone, and with the dynamic font introduced in iOS 7 (which allows apps that support this feature to respond to the user's system global font size settings and make adjustments), automatic layout becomes increasingly important. With automatic layout, font adjustment is also easy to fit.
There's a trick to learning automatic layout: Practice makes perfect, and the next tutorial will take you to the auto layout.
Hello, constraint.
Close the current project and try the single View application template to create a new iphone project named "Constraints".
Any new projects created by Xcode 6 use Auto Layout by default and do not have to be turned on manually. To simplify this section, open Main.storyboard in your project and disable size Classes.
First, drag a new button, and notice that the blue dashed line is displayed when you drag on the panel, which is called the Auxiliary Line (guides):
There are auxiliary lines near the edge of the screen page and in the center:
If you've ever used interface Builder, you must have seen these guides, which are helpful in arranging and aligning views.
Note that there are no constraints when adding new objects to the view! But how does that come about? We just learned that automatic layout requires enough constraints to determine the location and size of all views, but now there are no constraints. Which means the layout is not complete now?
In fact, if you don't take any constraints, Xcode automatically assigns a default set of constraints, automatic constraints (automatic constraints), but not at design time, but rather when the app compiles. Since Xcode 5, automatic layout has been designed to allow developers to focus on designing the interface, rather than interfering with the developer during the design process, which is pleasing.
Automatic constraints give the view a fixed position and size, which means that the coordinates you see in storyboard are very handy, because you can largely ignore the automatic layout. You can create constraints only for parts of the view that have special needs, and the rest can be left intact as long as they can be done.
OK, let's play and see what constraints can do. The button that you just dragged up is in the upper-left corner, unconstrained. Make sure the button is aligned with the two guides.
Use the Editor/pin menu to add two new constraints to the button, and the result looks like this:
Did you guess? The two constraints are the first interval from the parent view (leading space to Superview) and the top of the parent view (top space to Superview).
All constraints are listed in the Document Outline panel on the left-hand side of the Interface Builder window:
There are now two constraints: one is the horizontal interval between the left edge of the button and the main view, and the other is the vertical interval between the button and the top edge of the main view. These two constraints are expressed in relation to:
The button is always 20 points from the upper-left corner in the parent view. ”
Note: In fact, these two constraints are not very useful in the scenario just now, because the results are the same as automatic constraints. In this case, if you just want the button to always be at a distance from the upper-left corner of the parent view, you can also completely add no constraints and let Xcode use the default automatic constraint.
Now select the button and drag it to the upper right corner of the scene, as well as the Blue auxiliary line:
What the hell is that orange thing, lying trough? This indicates that the position size of the button in Interface Builder is no longer consistent with the position size expected by the automatic layout, called View dislocation (misplaced view).
To run the app, the button still appears in the upper left corner of the screen:
Orange is an error for automatic layout. Two orange squares are displayed in Interface Builder: one solid line with dashed lines. The dashed box represents the view frame according to the automatic layout, and the solid wireframe represents the view frame according to the position laid out in the scene. The two should agree, but there are differences.
How to fix this problem depends on your actual intent:
-
Want to place the button on the left 254 point? In this case, it is necessary to increase the existing horizontal interval constant by 234 points, which is the meaning of the orange marker that says "+234".
-
Want to change the button to the right? In this case, you need to delete the existing constraint and create a new constraint.
Deletes a horizontal interval constraint. First select it in the Panel or document outline, and then press the DELETE key on the keyboard.
Note the Orange box around the button, and the Red dot-line box. The Orange Box tells you that the layout is wrong, and the red dot-wireframe tells you where the auto-layout thinks the button will appear at run time. This occurs because the constraints required to calculate the button position are incomplete, and you also need to add constraints to the horizontal position.
You might want to know why Xcode isn't adding automatic constraints in a horizontal position, because Xcode creates automatic constraints for them only when no one is constrained. In other words, once you manually add a constraint to a view, Xcode will give you the layout constraint settings for that view. Xcode does not create any automatic constraints for it at this point, but instead lets you add additional constraints to the layout that you need for the view.
Select this button and select Editor/pin/trailing Space to Superview. This creates a new constraint between the right edge of the button and the right edge of the screen, and the current relationship for all constraint representations is as follows:
The button is always 20 points from the upper-right corner in its parent view. ”
Run the app, switch to landscape mode, and note that the button will keep the same distance from the right edge of the screen:
When you place a button (or other view) on a snap guide and add a constraint, you get a preset interval constraint, defined by the Apple Official document iOS Human Interaction Guide (iOS Human Interface Guidelines, HIG). For near edges, the standard size of the spacing is 20 points.
Now drag the button to the left for a distance:
The orange dotted box appears again and the view is misaligned. Suppose we want to put the button in this new position, after all, it's not uncommon to have the view fine-tune a few pixels after the constraint is set, but there's a workaround to delete the existing constraint and create a new constraint, but there's a quicker way.
In the Editor menu, there is a resolve auto layout issues (dissolve the automatic layouts Problem) submenu, where you select Update Constraints (updating constraints). In my case, the command will tell interface Builder to increase the corresponding constraint by 64 points, as follows:
OK, the constraint turns blue again, the layout is valid. You can see in the document outline that the horizontal spacing constraint is not a predetermined standard spacing.
So far we have been fiddling with the horizontal and vertical spacing constraints, followed by the center constraints. Drag a New button object near the bottom center of the panel so that it absorbs the guides:
To make the button always be centered horizontally relative to the parent view, you need to add a constraint that is center x Alignment (aligned with the X axis). Select Align/horizontal Center (Align/level center) from the Editor menu and an orange line will appear on the panel.
The long line is orange because you only set the x-coordinate related constraints for the button, and the y-coordinate has not been specified. Add a constraint to the Editor/pin menu so that the button is separated from the bottom for a distance, like this:
Did you choose the right one, just add the bottom Space to Superview constraint. This vertical spacing constraint keeps the button at a distance from the bottom edge of the parent view (the default is standard spacing).
Run the app and cut to the horizontal screen mode. Now in landscape mode the button will also be centered at the bottom of the screen:
What was done before is to express the intention of "the button is always located at the bottom center". Note that you do not need to tell interface Builder the exact coordinates of the button, just describe where you want it to be in the view.
Since the automatic layout has been used, you should never worry about arranging the exact coordinates and sizes of the view, which, in contrast, automatically calculates a reasonable coordinate and size based on the constraints you set.
The difference between the automatic layout and the previous one in the Dimension checker is the change in mindset:
If you do not use automatic layout, enter the x-coordinate, y-coordinate, width, and height values in the corresponding fields to change the position and size of the selected view. If you use auto-layout, you can still enter a specific value in it, but doing so would cause the view to be misaligned if the view already has constraints, and you need to update the constraint to match the new value.
For example, if you set the button width value to 100, the panel will appear as follows:
Xcode clearly says, "want to set the width to 100 points?" No problem, but you know it's not binding. ”
Here we assume that you really want to set the button width to 100 points. There is a special type of constraint on this: the fixed width constraint. The undo action is performed first, the button is centered, and all the constraints are blue. Select the button and select Editor/pin/width to add a "beam" below the button:
Select this "beam" and set constant to 100 in the property inspector, which forces the button width to be set to 100 points, regardless of the text size. For easy identification, you can set the background color for the button:
You can also see this width constraint in the document outline on the left:
Instead of saying that the button is different from the parent view spatial relationship, the width constraint is only valid for the button itself, and perhaps you can view it as this button and ... Its own restraint (laughter).
You might ask, why didn't the button have a width constraint before? How does automatic layout determine the width of a button without a width constraint?
The truth is only one: the button knows how wide he is. The text of the button appends the reserved space, which is the basis for calculating the width. If you set a background image on the button, the picture will be taken into consideration.
This is the intrinsic content size (intrinsic contents size). Not all controls have this concept, but there are also many (such as Uilabel). If a view is capable of calculating its own dimensions, you do not have to specify a width constraint or a height constraint for it. We'll mention it later.
To get the button back to its optimal size, remove the width constraint, then select the button, select size to fit content in the editor menu (to fit the contents to set the size), and restore the intrinsic content size of the button.
A slap doesn't ring
Guides exist not only between parent and child views, but also between different views at the same view level. Let's take a demonstration, add a New button to the panel, and then drag the button, and you'll notice that the guides appear near the other buttons.
Drag the New button near the existing button to make it snap to the guides:
There are several auxiliary lines here, and Interface Builder will recognize the different alignment of two buttons: top, center, or bottom.
Xcode 4 May convert the auxiliary line adsorption state into a new constraint, but starting with Xcode 5, if you want to set a constraint between two buttons, you need to create it manually, just like before in the Editor/pin menu, there is a quicker way.
With the New button selected, control-drag to the other button:
Release the mouse button, will pop up a menu, click the first option, horizontal Spacing (horizontal interval).
The action creates a new constraint:
An orange box appears, and the button requires additional constraints. The size of the button can be automatically inferred from the intrinsic content size, and the x-axis position constraint has just been added, and the rest is the y-axis position constraint.
It's easy to tell what the missing constraints are, but it may not be obvious in a more complex design. However, Xcode has already seen through everything, will clearly point out the lack of constraints, it is really helpful.
There is a small red arrow next to the view Controller scene in the document outline, and clicking on the arrows lists all automatic layout problems.
Not bad! Without the y-axis position constraint, we'll fill it up. Control-Drag the new button down to the container view:
This pop-up menu is a bit different. The options in the menu are determined by the environment, which depends on the relevant view and the direction of the mouse movement. Select Bottom space to Bottom Layout guide (at the bottom of the bottom layout indicator line). Top/bottom Layout Guide is the upper and lower edge of an arrangement that takes into account the inherent interface features (such as page bars, toolbars, navigation bars, and so on), for example, when a page bar is present at the bottom of the sheet, and the top edge of the layout indicator line coincides with that of the page bar, and when no columns exist on the page, The bottom layout indicator line is coincident with the bottom edge of the screen. )
The New button now has a certain vertical interval from the bottom of the screen and a certain horizontal interval between the other buttons. Because the space is relatively small (only 8 points), the "beam" may be somewhat unclear, but it does exist.
In the document outline, click Horizontal Space (8) Constraint:
This constraint exists between the two buttons and the meaning of the expression is:
"No matter where and how big the first button is, the second button always appears to the left of the first button. ”
Select the button on the right to increase the text, such as "A longer label". When you're done, the button will make room for the text, automatically resize, and the other button will squeeze it away. After all, set a constraint that is relatively fixed to the left of the first button.
You can continue to try and feel how the constraints work. First, set the background of the longer button to yellow, and then drag a button over the yellow button to allow it to snap to the auxiliary line vertically (don't let the left edge of the two buttons align).
To clearly identify the actual extent of the new button, set its background to green.
Two buttons (with auxiliary lines) are adsorbed together, so there is a standard interval of 8 points recommended by HIG. Control-drag between buttons, then select Vertical Spacing in the popup menu to convert the standard interval to a constraint.
Controls are not limited to standard intervals, and constraints and views are real objects, which means that the properties of the constraint can be modified.
You can select the Vertical spacing constraint by clicking the "beam" between the two buttons in the panel. Of course, this is a bit of a hassle, the simplest way is to choose in the document outline. Select the constraint and then cut to the property Inspector:
In the constant field, enter 40 to modify the constraint size.
Run the app, cut to landscape mode, watch the layout effect, and add a cross-screen preview assistant as before:
The vertical orientation of the button is maintained and the horizontal direction is not. For obvious reasons, the green button has not yet set the x-axis position constraint.
For this issue, it is not appropriate to add a horizontal spacing constraint from the green button to the left edge of the screen, so that the button in landscape mode will maintain the same x-coordinate and look awkward. So, we need to express this intention:
The yellow button is always centered horizontally, and the green button is aligned to the left edge of the yellow button. ”
The constraint on the first condition has been set, so let's take care of the second one. Interface Builder Displays the alignment guides, dragging the buttons above so that the left edge snaps to the alignment guides of the yellow button.
Finally, hold down CONTROL and drag between the two buttons and click left in the menu. This creates an alignment constraint that indicates that the left edge of the two views is always aligned, in other words, the x-coordinate of the two buttons remains consistent. Constrained to blue, layout problem solved.
Run the app, cut to landscape mode, or verify that the layout is valid in the Preview assistant:
Swift language auto layout Getting Started Tutorial