IOS6 Automatic layout Getting Started –auto layout (GO)

Source: Internet
Author: User
Tags dashed line

IOS6 Automatic layout Getting Started –auto layout (GO)
Tags: gossip

So far, even if your interface design is within reasonable complexity, you have to write a lot of code to adapt to the changing layout. Now I'm sure you'll be glad to hear that this will not happen-for iphone and ipad IOS6 has brought a very remarkable feature: automatic layout.

The automatic layout not only gives your application a wide variety of screen-size design support, but also provides additional surprises, as well as the ability to support a variety of small-scale design tasks such as multi-lingual environments. You never have to redesign the nibs and storyboards files for the languages you want to support, including some languages written from right to left, such as Hebrew and Arabic.

This tutorial will show you how to get started with Iterface builder for automatic layout. In iOS 6 by tutorials, we've written this tutorial a lot deeper, and based on this knowledge there's a whole new chapter that you'll see if you release the full functionality of the automatic layout through code.

All right, now start with your favorite snacks and drinks, and get ready to be the master of automatic layout!

Springs and Struts problems

There is no doubt that you may be more familiar with autosizing masks-this is the "springs and struts" pattern. Autosizing mask determines what happens to a view when its superview changes size. Does it have the flexibility and automatic repair of the page edge processing capability (the struts), and what will happen to its width and height (the springs)?

For example, when the width of a view's superview is wider, its width is also flexibly widened, and its right edge is automatically fixed to the right edge of the Superview.

Autosizing the system to handle this simple situation is good, but when the situation is slightly more complicated, it will quickly screw up your layout. Now let's look at a simple example of a springs and struts pattern that can't be handled.

Open Xcode to create a new project based on the single View application template, name it "Strutsproblem", select iphone program and disable storyboards:

Click Open Viewcontroller.xib in Interface Builder. Before you do anything else, please disable auto layout in nib first. You can find this option in File Inspector:

Deselect the Use AutoLayout check box. Now your nib is using the old version of the struts-and-springs mode.

Tip: Any new nib or storyboard file that you create with Xcode4.5 or later will use Auto Layout by default. Because the Auto layout feature is only available in iOS 6, if you want to use Xcode4.5 to do some IOS5-compatible apps, you'll have to deselect ' use AutoLayout ' in the new nib or storyboard file. check box to disable Auto Layout.

Drag three new view to main view:

To make the look clearer, we fill each view with a color.

Now each view is points far from the boundary of the form, and the distance between the view of each fill color is also points. The bottom view is 280 points wide, and the top two view is set to a width of points. All the view settings are set to a height of points.

Run the program and rotate the simulator or your device to the landscape direction. Your device will be as so, and our ideal gap is very far:

Tip: You can rotate the emulator by using the menu option Hardwarerotate left and Rotate right, or by holding down CMD and then using the Leftwards or right arrow keys to rotate.

And what I want is to let the program run after it looks like this in the landscape direction:

It is clear that autosizing masks need to do something else to achieve the desired change in the three view. Start setting up autosizing from the view in the upper left corner:

This step enables the view to be positioned next to the top and left edges (not the bottom and right edges), and supports scaling both horizontally and vertically when the Superview changes its size.

Similarly, change the upper-right corner of the autosizing setting:

This is the setting for the bottom view:

Run the program and turn the device to landscape orientation. Now it should look like this:

It's close to the ideal, but it's a little flawed. The distance between the three view (s) is incorrect. Also look closely, the size of these three view is not 100% correct. The reason for this is that autosizing masks know to change the size of the view when Superview changes, but it does not know how much to change the size.

You can play with autosizing masks-For example, change the wide and high values that can be changed ("Springs")-but you will almost never be able to set the exact distance to 20-points between three view.

To solve the problem of changing the layout using the springs and struts, unfortunately, you have to write some code to do it.

UIKit will send some messages to your view controllers when the user interface starts spinning, during and after the rotation. You can change the layout of your user interface by listening to these messages. Often you rewrite willanimaterotationtointerfaceorientation:duration: To change any frame of view that needs to be re-planned.

But before you start doing this, you first need to declare the outlet attribute inside the views.

Xcode switches to the Assistant Editor mode (a button in the middle of the Editor toolkit in the upper-right corner of the Xcode toolbar) and then drags each view to the view controller:

Connect the view to the attribute one by one:

@property (Weak, nonatomic) Iboutlet UIView *topleftview; @property (weak, nonatomic) Iboutlet UIView *toprightview;@ Property (weak, nonatomic) Iboutlet UIView *bottomview;

ADD the following code to VIEWCONTROLLER.M:

-(void) Willanimaterotationtointerfaceorientation: (uiinterfaceorientation) tointerfaceorientation Duration: (nstimeinterval) duration{[Super Willanimaterotationtointerfaceorientation:tointerfaceorientat    Ion Duration:duration];  if (tointerfaceorientation = = Uiinterfaceorientationlandscapeleft | |        Tointerfaceorientation = = uiinterfaceorientationlandscaperight) {CGRect rect = self.topLeftView.frame;        Rect.size.width = 210;        Rect.size.height = 120;        Self.topLeftView.frame = rect;        rect = Self.topRightView.frame;        rect.origin.x = 250;        Rect.size.width = 210;        Rect.size.height = 120;        Self.topRightView.frame = rect;        rect = Self.bottomView.frame;        RECT.ORIGIN.Y = 160;        Rect.size.width = 440;        Rect.size.height = 120;    Self.bottomView.frame = rect;        } else {CGRect rect = self.topLeftView.frame;        Rect.size.width = 130; Rect.size.height = 200;        Self.topLeftView.frame = rect;        rect = Self.topRightView.frame;        rect.origin.x = 170;        Rect.size.width = 130;        Rect.size.height = 200;        Self.topRightView.frame = rect;        rect = Self.bottomView.frame;        RECT.ORIGIN.Y = 240;        Rect.size.width = 280;        Rect.size.height = 200;    Self.bottomView.frame = rect; }}

This callback function is called when the view controller is rotated to a new direction. Now when the user interface is rotated, the view controller zooms in on the view size in it-a hard-coded ability to understand the size of the iphone's screen. Because this callback function occurs in an animated block, it can be animated when changing its size.

Wait, you can't run the program now. You must first restore these three view autosizing masks settings as shown, otherwise the autosizing mechanism will conflict with the location and size of the view you have in the Willanimaterotation: function settings.

You can now run the program and then flip the device to landscape orientation. You can see the rendering of each view is ideal, again to turn the screen to portrait direction, it looks good.

That's a success, but you'll have to write a lot of code for such a simple presentation. Imagine that when you encounter really more complex, especially dynamic ones, those independent view changes in size, or there are a series of subviews that are not fixed when you need to make effort in the code.

Tip: You can also use a different method, which is to do both the portrait orientation and the direction of the landscape nib, and then when the device rotates, the corresponding view from the nib file loaded into, the current view swap out. But even then, you still need to do a lot of work, and you also have to manage two nib files rather than a nib file.

Auto Layout to save!

Now I'm going to show you how to do the same with auto layout. First, put willanimaterotationtointerfaceorientation:duration: This method is removed from the VIEWCONTROLLER.M, because the current I want to do the auto layout is no need to write any code.

Go back to Viewcontroller.xib and in the File Inspector Control Panel, tick the "Use AutoLayout" checkbox to make auto layout work on the nib file:

Tip: The Auto Layout feature is always on in the entire nib or storyboard file. All view in both files will use the Auto layout function if you tick the box.

Now run the program and turn the screen, the appearance is still the previous chaotic sample.

Now let's start the auto layout feature. Press and hold the CMD key while the top two view (green and yellow) is selected. From the editor menu of Xcode, select Pinwidths equally:

Re-select the two view and do the Editorpinhorizontal spacing operation again. (even though the two view looks like it was selected when you do the first pin operation.) Note, however, that they are currently in a special layout-relationship display mode, and you still have to re-select the two view. )

In the document overview on the left, you will notice that there is a new section called "Constraints". This section is automatically added when you enable auto layout in the nib file. In the next section of this document you will learn what these contraints are and how they operate.

Now, we remove a list from the constraints named "Horizontal Space (170)":

Run the program and turn the screen. It looks much better now – the top two view has the right width and spacing – but not the way we want it to be:

Press and hold the CMD key while selecting all three view. In the menu bar, do pinheights equally operation.

Now hold down the CMD key while you select the upper-left and bottom view, and then do the editorpinvertical Spacing operation.

Finally, remove "Vertical Space (240)" from the constraint list.

If you select all of the three View,interface builder at once, it should look like the following:

The blue T-Shape object defines the limits between the individual view. This may seem a little complicated, but once you've learned it, you'll find this expression quite concise and straightforward.

Run the program ... Wow, I didn't write a line of code. Everything looks great!

Cool, but what have you done just now? Auto layout allows you to simply express the relationship between the views in the page layout without letting you make a lot of code for the various views and where they are located.

You have just done the following relationship operation – that is constraints– in the page layout:

    • The upper-left and upper-right corner of view (that is, the first pin widths equally operation).
    • There is a 20-point between the upper-left view and the top-right view (the corresponding action is pin horizontal spacing).
    • All view is the same height (the corresponding operation is pin heights equally).
    • There is a 20-point gap between the top two view and the bottom view (the pin vertical spacing).

These are enough to show how Auto layout places the various view in the layout and how it works when the screen size changes.

Tip: Springs-and-struts Layout mode also brings some additional restrictions when you switch from it to "use AutoLayout" mode. There is basically a limit to the margin between the view and the edge of the screen: "This view is always 20-points from the top/bottom/left/right." ”

You can see all of your contraints in the document summary. If you click on a constraint,interface builder in the document profile, you can highlight it by drawing a white border and adding a shadow to it in the place where contraint is reflected in the view:

Constraints are real objects (belonging to the Nslayoutconstraint Class), and they also have corresponding properties. For example, select the top two view spacing constraint (named "Horizontal Space (20)") and switch to its attributes inspector. Now you can change the distance between two view by modifying the value in the constant.

Set it to 100 and run the program. Now the distance between the two view is wider:

Auto layout is much more expressive than springs and struts when your program needs to describe various view layouts. In the remainder of this tutorial, you will learn all about constraints and how to use it in Interface Builder and make it possible to do various layout arrangements.

How Auto Layout works

Just like the test you saw above, the basic tool for Auto Layout is constraint. A constraint describes the relations between the two view. For example, you might have a constraint like this:

"The right boundary of lable A and the left boundary of Lable B are connected with the blank of the points. ”

Auto layout uses all of these constraints to do some math calculations on all your view so that the view achieves an ideal position and size. You no longer need to set the Frame-auto layout of the view to help you do all this-based solely on the constraints you set for view.

Before auto layout, you always set the frame of the view by hard coding, or you can place them precisely through the interface Builder coordinates, through initWithFrame: To pass a rectangle, or by setting the view frame, Bounds or the center property.

For the application you have just made, you have specifically set frames to the following:

You can also do autosizing masks settings for each view:

That should not be the way you think of screen design. With Auto Layout, all you have to do is to do the following:

Now the size and position of the view is not so important; Give the constraints the questions. Of course, when you drag a new button or tab into the canvas, the control has a specific size and you put it in a specific location, but it's also a design purpose to tell interface Builder where to place the constraints.

Designed to look the way you want

A huge advantage for you to use constraints is that you no longer have to tinker with the coordinate system to make your view appear in the right place. All you have to do is to describe the relationship between each view by using auto layout. This design method is called design by purpose.

When you design by purpose, you are expressing what you want to achieve and not how to accomplish the goal. In the past it would have been this: "The coordinates of the upper-left corner of this button are (20, 230)", and now you can say:

This button is centered vertically in its superview, placing him in a fixed position off the left edge of its superview. ”

Using this description, auto layout can automatically calculate where your button should appear, regardless of its superview size.

Here are other examples designed by purpose (Auto Layout can handle all of these instructions):

"These two text fields should remain the same size. ”
"These two buttons should keep moving at the same time. ”
"These four labels should be aligned on the right side at the same time. ”

This makes your user interface design appear more descriptive. You simply define the constraints and the system will automatically calculate the frames for you.

In the first part you see that there is a lot of work to be done to make a page layout with only a few view points displayed in the two directions of the iphone at the same time. But if you use auto layout to do it, you can save that aspect of strength. If you set the constraints properly, the layout will be displayed automatically without requiring you to make a slight change in the portrait orientation and view direction.

An additional important benefit to using auto layout is internationalization. For example, the word character, is the name of the long, put it into your label will be a very headache. But once again, auto layout will save you because it can help you automatically scale the labels based on what your content needs to perform-everything else will be adjusted according to constraints.

Added support for German, French, and other languages to do is simply set your constraints, translating the text, just so Oh!

The best way to get started with Auto Layout is to play with it. That's the rest of the tutorial.

Tip: Auto Layout is not only useful for direction rotation, it can also easily pull up your user interface to accommodate different screen sizes. This is not a coincidence! The technology was added to the ISO when the iphone 5 's long screen appeared. Auto Layout makes it easy to fill up the extra vertical screen content of your iphone 5. And God knows there will be a rumor that the "IPad Mini" appears ... At least you can now use Auto Layout to prepare for the future.

Fall in love with constraints

Turn off your current project and create a new project using the single View application template. The named item is "Constraints". Then select for iphone project and do not use storyboards, but we need to use arc.

A new project created using Xcode4.5 will default to you to start auto Layout, so you need to do anything special to enable it.

Click Viewcontroller.xib to open Interface Builder. Drag a new rounded button into the canvas. Note that when you drag and drop, the blue dashed line will appear. These lines are considered to be guides:

These guides will be displayed on the page side of the screen and will also appear in the Center:

If you've used interface Builder before, you'll undoubtedly be familiar with these guides. They can be very helpful when you want to do something about it. When Auto Layout is enabled, these guides have different meanings. Of course you still need them to help you with things, but at the same time they will tell you where the new constraints will be.

Put the button on the guides and put it in the upper left corner. Now the nib file will look like this:

Look, there are two blue things attached to the button. These T-shaped objects are the constraint that are set on this button.

All constraints are also listed in the document Summary panel on the left side of Interface Builder:

We currently have two constraints, there is a horizontal space between the button and the left edge of main view, and there is a vertical space at the top of the button and main view. This relationship is represented by constraint as:

"This button will remain in the upper left corner of its superview. ”

Now check this button again and put it in the top right corner of the nib file, or the Blue guides:

Now the constraint value of horizontal Space has changed. It is no longer attached to the left edge of the button but to the right edge.

When you place a button (or any other view) on the guides, you get a standard size, which is defined in "HIG", which is Apple's iOS Human Interface guidelines document. For margins on the edge of the screen, the standard size is 20-points blank.

Even if you put the button in some place where there is no guide, you will still get a horizontal or Vertical space constraint. Try it. Then move the button like a little left to get the effect:

At present there is a horizontal space constraint. In the document profile, you can see that there is no standard space now.

Where your button is placed, you will get a corresponding constraint.

There is also a "center" of the constraint. Drag the button to the center of the bottom of the canvas so that he can snap to the center guides:

Please note that this horizontal Space constraint is now replaced by a center X Alignment constraint, which means that the button will follow its Superview center on the horizontal axis. There is still a vertical Space constraint value that keeps this button at the bottom of the view. (Use standard margins, too).

Run the program and turn the device to landscape orientation. Look, even in the direction of the landscape, this button still stays in the center of the bottom:

For this button, this is what you want to say: "This button should always stay at the center of the bottom." "Please note that there is no place where you have to tell interface Builder what the coordinates of your button are, you just put it in the view."

With Auto Layout, you don't have to worry about the exact coordinates of your view in the canvas. All of this, Auto layout will help you derive from the constraints you set up (or interface builder set it all up for you).

In this example you can see the conversion of this button in size inspector, which is quite large:

When Auto Layout is disabled, the value in X,y,width or height changes the location and size of the selected view. When Auto Layout is enabled, you will still be able to enter new values in these boxes, but usually the result will not be the effect you want. The view will move, but interface builder will also calculate the new constraints based on your new value.

For example, changing the value of width to the 100,canvas inside the button will look like this:

Now the value of Center X Alignment constraint disappears, instead of a button attached to the left edge of the screen horizontal Space, this button also produces a new constraint, which forces the width of the button to be fixed at 100 Points (you can see the blue bar below the button).

You see a new width constraint now on the left side of the document profile:

Unlike other constraint, which are between the button and its superview, this width constraint can only be applied to the button itself. You can think of it as a constraint between a button and a button.

Drag the button so that it is stuck again on Center X Alignment constraint.

Tip: Because changing the position and size by size inspector may mess up your constraints, I recommend that you try not to do so, and change the constraints if you want to alter the layout.

You may now wonder why the button didn't have a width constraint before. In the absence of the case, how does Auto layout know to change the length of the button?

It is possible to explain that the button itself knows how much his width should be, and it can be calculated by filling it with a few rounded margins based on the caption text inside it. If you set a background picture of a button, it will also take this into account.

This phenomenon is considered to be intrinsic content size. Not all spaces will be like this, but most of them are (uilable not included). If a view can calculate its own preferred size, then you do not need to specifically set the width or Height constraints. You'll see much more about this.

To get the best size of the button, select it and set the size to Fit Content in the editor menu. This moves the button away from the explicit width constraint and restores it to the intrinsic content size mode of the button.

Tango with two buttons

Guides can appear not only in view and Superview, but also in multiple view of the same class. To prove this, please drag a new rounded rectangle button into the canvas now.

If you put this button away from the other one, this button gets its own constraints. However, if you put the two buttons close enough, the constraint of the two buttons will start interacting.

Snap the new button next to the original button:

Now there will be some dot-like guidelines, but interface builder won't convert them all to constraint, because that's a bit more. But this will basically recognize that the two buttons can be aligned in each direction-at their top, center, and at the baseline.

When you put the new button down, the constraints of the button will look like this:

, the New button has a vertical space for the bottom of the screen, there is also a horizontal space for another button. But this space is very small (only 8points), the T-Shape object may be difficult to see, but it must be there.

Select horizontal Space constraint in the document overview:

When you select a constraint, it is highlighted in the screen where it belongs. This shows a special constraint between the two buttons, which means saying:

The second button will always appear to the right of the first button, regardless of the position of the first button and how the size changes. ”

Select the left button and enter some words such as "A longer label". You will see that when the new title is entered, the left button is reset to its size, and the other button moves out of its original position. But it's always attached to the right edge of the first button, which is what we want:

Please note that Interface Builder re-uses a horizontal space instead of the original center X Alignment. Each time you make a change in the size (or position) of the control, Interface Builder calculates a constraint that it thinks is right. Generally speaking, it is all right, but sometimes it completely misunderstood what we meant. Here, you obviously want to keep the button in the center position when you change the text in it.

Put the button back into its center to the Zichu. See how the constraint is now:

This may not be what you want to happen. Now the two buttons are no longer connected to one another. Instead, the New Right button and the right edge of the screen have a horizontal space constraint. There is no horizontal space between the two buttons.

Of course, you can do this by snapping them together and then reconnecting them, but this problem can be avoided by not dragging the view.

First, the shortcut key cmd-z to cancel the operation, so that the first button is no longer center-aligned. Now select the button and select AlignHorizontal Center in Container from the editor menu. This time it was not just the first button moved to the center of the screen-the other one moved along. It is more likely that you should do so!

To have a better understanding of the concept, do more. Select the small button and put it on top so that they are captured in place vertically (but don't try to align the left edge of the two buttons):

Because you captured two buttons together, there is now a vertical Space between them. This pitch is still recommended by HIG 8 points far away.

Hint: This "HIG", is the abbreviation of IOS Human Interface guidelines, introduced Apple to design excellent user interface recommendation setting. Must be read for iOS developers ... HIG explains which UI elements are appropriate in which case, and provides the best examples to use them. You can check it out here.

You can have no restrictions on the standard distance between controls. Constraint is a fully fledged object, like a view, so you can also change its properties.

Select the vertical Space constraint between the two view. You can also do this by clicking on the T-shaped object, although it's a little too elaborate. But by far the simplest way to do this is by clicking on the constraint in the document's schematic. Once you have selected, switch to attributes Inspector:

The default standard attribute tick is selected. The space constraint between two objects is 8 points, and the margin between the superview of a view is points. Enter 40来 in the constraint box to change its constraint size. Look, now the two buttons are farther away, but they are still connected to each other:

Run the program to see the effect:

The buttons clearly keep their vertical distance arranged, but they don't have a horizontal orientation!

If you look closely at the nib file, you will find a horizontal Space between the button on the top and the left edge of the canvas (if you have the same button in the rough place at the same point as I did):

The bottom label is aligned horizontally in the screen, but the top button is not-it always stays the same distance from the left edge.

This is not ideal, in fact you want the result is the following goals:

The bottom button should always be centered horizontally, and the left edge of the top button is always aligned to the left border of the bottom button. ”

For the first constraint, you already have it, but the second one isn't. Interface Builder Displays the aligned guides, so you can drag the top button to the left until its boundary snaps to the bottom boundary:

Unfortunately, this operation moved the vertical Space between the two buttons (at least in some cases, depending on how the control was dragged and placed). Interface builder simply "forgot" that there was a vertical space, replaced by the operation is at the bottom of the view and regenerate a vertical Space:

It's too far from the result you want. The result should not be a vertical Space between the two buttons? Instead of creating a vertical Space at the bottom of the window.

IOS6 Automatic layout Getting Started –auto layout (GO)

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.