Learn to fall in love with iOS automatic layouts (auto layout)

Source: Internet
Author: User

This article translates from the Yari dareglia learn to the Love AUTO layout article

Ladies and gentlemen, let's start this tutorial with the right mindset: Automatic layout is simple!

It took me a while to master how the automatic layout worked, and now looking back, I found that I definitely overestimated the problem. In this article I will cover some basic aspects and some techniques that I'm sure will help you when facing automatic layout without fear.

Xcode4

Before XCODE5, auto-layout could be the most annoying "feature" you've implemented in your app. The tag "Use auto layout" is like saying "Make me crazy". That's why I never tick this mark. Feel ashamed of yourself!

But in Xcode5, the situation becomes completely different, if you still have nightmares about the automatic layout in Xcode4, well, forget them!

Simply describe the automatic layout

With automatic layout, you can use the relationships between UI elements to organize your app's interface. These relationships are called constraints.

At first, this sounds hard to understand, because we all place each sub-view independently, just consider modifying the Frame/bound property to determine where the child view is and how to draw it.

This is the first goal of this article: discard outdated habits of backwardness!

Introduction to the interface of automatic layout in XCODE5

We can set the relationship of automatic layout through code or the help of Interface Builder tools. I'll introduce the automatic layout in the form of the code in the next example, but now we're just going to introduce the visual Setup interface provided by Xcode to make things easier.

Create a new iOS project and open the storyboard (storyboard). In the lower right corner you can see a set of buttons for automatic layout. I will parse the functions of these buttons in the code below, and now just remember that the buttons are about automatic layout.

Another approach is to interact with the automatic layout directly through the view. After you drag a UIView onto the view controller, press CTRL + click UIView and drag the mouse. You should see a blue choice. You are already familiar with this because it is the same as the one we use to connect iboutlet/ibaction, but this time if you release it in the new view (that is, the uiview that you just dragged), you will see some new choices.

Let's add a constraint to the view we just created. * *. crtl+ Click on the top of the view

Drag the mouse to maintain a horizontal trajectory. This ensures that the "width" parameter is displayed. When you release the mouse button in the same view, you can try to move vertically to get the height parameters (I personally think this behavior is an option with a good user experience).

Select the width parameter

Now you have created a constraint that says, "What is the width of this view?" Ignore the red/orange lines that are drawn in the view. We only need this constraint to look at some of the other Xcode features.

Select this uiview and open the Size Inspector Control Panel in the right column

You'll find a new area called constraints, which in our case contains the width constraint we just added.

Note: Sometimes you don't see a width or height constraint parameter, but instead find a "leading space to" thing, which is just a bug, deselect it, and then re-select the corresponding view to get the correct parameters.

From here, you can modify the constraint or delete the constraint by using the settings icon next to it.

Another you can find information about your constraints can be found in the document outline, on the left side of the storyboard, you can click on the button below to open this section

As you said, we can completely navigate through all the constraints we just created. Click on it and the constraint will be highlighted in the View editor. Another useful information we get from the document outline is whether the constraints set are inconsistent or incorrect. The red circle and white arrows that appear in the upper-right corner of the document outline tell us that some constraints are not set correctly.

Click on the arrow and a new view will show up and show the details and errors.

Just click on the first red dot. Xcode is smart enough to advise you on the correct automatic layout configuration. Click Add missing constraint and Xcode will automatically add some constraint parameters to the view, and all errors will disappear.

If you click on this view again, you will see your constraints, but then these constraints will turn blue. This means that all required constraints are already defined, and the automatic layout fully understands how to draw your view.

Example 0: Introducing Constraints

Now that you know how to interact with Xcode to manage constraints, we can use auto-layout to practice and learn how it works.

The main rule we should keep in mind is that by specifying the location of a view through automatic layout, we need to give it a constraint on the X/Y position and the width/height dimensions. This is the first step in normal work.

Open the project file for this tutorial and check the EXAMPLE_0 result controller of the main storyboard. You can easily switch between all instances through the Document Outline window.

This is the final result of the first example: a UIView is always centered in the vertical and horizontal direction, regardless of the direction of the screen's rotation.

Now you can create your own project or simply use mine (you can find the source code at the end of the article). Here I have created all the examples of this tutorial (named Example n START) and the initial settings for thefinal result (named exampleN result).

Move your eyes to Example_0 START

In this case, you can find a yellow uiview that is a child view of the master. I set the view size to 150x150, I put it in X 85 and Y209 (just follow the Blue Nav line). I like to do this: before adding any constraints, we define the size and position of the view. The constraint is set only after these initial settings have been completed.

Now let's use 2 different methods to add dimension constraints. As we did in the previous section, CTRL + click the new view and drag the mouse horizontally to add the width constraint.

Now, to join the height constraint, we can use the icon in the lower right corner. First select the yellow UIView, then click the icon with the height parameter with the + flag, and then click the Add Constraint button. This is just another way to set a constraint.

We have defined this size constraint.

Click the red circle in the document outline to get questions about our view settings.

As I said, we need to set the width/height and x/y to meet the requirements of the automatic layout, and Xcode will help us to emphasize what is currently not set.

We can call Xcode to help us resolve these errors automatically, either by clicking the "Add Missing Constraint" button or by manually adding the effect. Let's add it manually this time to see how to create a relationship between the parent and child views.

Again, we can choose two ways to add a constraint:

CTRL + click on the UIView view, but this time the mouse remains perpendicular to the path to drag to the parent view of this view before releasing.

Select "Center horizontally in the container". You can verify this new constraint in the size checker called "Align Center X to:superview".

To add a vertical (Y) constraint, we use the first icon that shows the alignment constraint option. Click this button, tick the "Vertical Center in Container" tab, and then click "Add Constraints" to confirm the addition.

You should see two new blue lines running through this view, and now all the required constraints have been created.

Start the app and switch between the horizontal and vertical screen modes.

That's great, the yellow view stays in the center position.

(You can see the difference by removing the constraints, and in landscape mode, the view runs out of the screen.) )

Xcode Help

Another interesting feature is the ability of Xcode to reset frames and constraints when automatically managing your automatic layout settings.

In the previously set constraints, move the yellow view to a new location (just enter x=120,y=240 in the size settings panel without changing the constraints). You should see a screen similar to the following:

Your position constraint becomes orange, which means the view is misplaced, a red, highlighted dashed square represents the desired position of the view, and two tabs show the distance from the current view to the desired view position.

In the document outline, you can see a lot of information, when the indicator is not red, but orange, indicating that this is a view dislocation is a warning, not an error. In fact, automatic layout constraints still work, even if the contents of the storyboard you see are different from the results you run.

So, how do we solve this problem? First you need to make sure what you want to do with the results.

Do you want to keep the original settings?

If yes, click on the button below:

Then select "Update Frame", which will move to the location of the runtime (the red dashed position).

Do you want to update the location of the runtime?

In this case, also click on the button above and select "Update Constraints" to change the constraint to fit the current position.

Try it out and see the difference between the two.

Example 1: Fixed content size

Okay, go to example.1result view controller.

In this example, we want to use Uilabel to get results like example_0.

Move to Example_1 START, and then just add a location constraint (if you find you don't know what to do, go back to the third step of the example above).

Yes, you've done it! You can check the results by launching the app. This tag is placed completely in the middle of the window.

Wait a minute, you might ask, is that size constraint not set as above? Yes, we don't need it! Also, setting the size constraint is considered an error.

These objects, like buttons and labels, are sized according to their content. A specific method

Returns the size information for this type of view, so you do not need to overwrite the information with constraints.

In this tutorial, we don't discuss the automatic layout of custom views, but if you want to create a view that automatically adapts to size, you should understand this method in more depth.

Example 2: UI independent of screen size

When we create a view for a 3.5-inch and 4-inch screen, or create a constraint for a horizontal screen and a vertical screen, it will be different.

Go to example_2 RESULT. I want you to show a really common situation: set up a layout that works in any screen size and screen orientation.

Run the application under IPhone4 and IPhone5, and change the orientation of the screen respectively. You'll see that the layout fits perfectly to the size of the screen.

You already know how to put a label in the middle, but what about the blue view at the bottom of the screen? Let's go to example_2 START. You can set this tag as you do in practice, and this blue view has two aspects that we must consider:

    • Its width varies depending on the size of the screen
    • He's taped to the bottom of the screen.

Let us remember the first rule that we have to satisfy both the position and the size of the constraint.

First thing, set the desired position by moving the blue view at the bottom of the screen.

We can easily set the height constraint just (press CTRL + click) to drag the view vertically and select the "height" or the bottom icon, as I've shown you before.

What about the width? We want it to be related to the parent Class View, in order to do this, we need to create two relationships:

* Keep its left distance from the left side of the parent class at n distance * Keep its right distance from the right side of the parent class at n

The two relationships automatically set its width based on the size of its parent class.

In order to create these relationships, we can CTRL + click on the blue view, move to the left side of the parent Class View to release, and select "Leading Space to Container" and select "trailing space to container" on the right.

Now that we have all the size constraints, let's set the position.

Once again, I need to define a constraint for the Blue view that points to the parent Class View. This is very simple and the relationship is simply:

* Keep it at the bottom of the parent class with a distance of 0

This information is sufficient to define the vertical position of the view, because the position of the parent class is always defined.

So we add this constraint as we did earlier: CTRL + click View, drag to the bottom of the parent class, and select bottom space to bottom layout (you can release the mouse on the Blue view).

Note: You can also drag directly in the document outline, in which case you can see all possible constraints.

At this point, all of the relationships we need to meet the needs of your simple interface.

Example 3: Updating constraints in code

Sometimes, for more complex interface locations, we need to control more constraints. A constraint is an instance of a Nslayoutconstraint class, and we can obviously access constraint-related properties at run time through code.

Go to Example_3 RESULT. You will see a white label aligned to a red view. If you run this instance, when you switch between a horizontal screen and a vertical screen, the Red view will change its height depending on the size of the screen.

Let's see how this is done!

* * Move to Example_3 START. Add constraints to the bottom red view

* Set the leading space and Trailing space with the parent class to define the width according to the parent class

* Set the space at the bottom of the parent class so that the bottom of the red view is pinned to the parent class.

* Set height (remember?) CTRL + click, vertical line track).

If you have completed the steps above, the result is a blue constraint line as follows:

Add the following constraint to Uilabel

* Horizontal Center Tab (Ctrl + click Tag, drag horizontally, release mouse and select correct constraint)

* Define the distance between a label and the bottom view (Ctrl + Click the tab, drag the view to the end and then release, then select "Vertical Spacing").

Now you should also define the constraints required by Uilabel.

At this point, if you run this example, you will see that the bottom view is not automatically resized in the vertical direction. Sure, we didn't set any constraints to make it this way, so let's set it up.

I have associated the Resizerviewcontroller class to this view controller. Open RESIZEVIEWCONTROLLER.M and you will see the first attribute:

Let's associate this outlet to the height constraint we just added.

So open storyboard again, from the document outline, in the Example_3 start line above CTRL + click, and drag to the height constraint, release the mouse, so that you can associate it up.

Now we just need to update the value of this constraint.

*6. Open the resizerviewcontroller.m file and check for this function:

?

1 2 3 4 5 6 7 8 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{           if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {                 self.CS_BottomView_Height.constant = 100;           }else{                 self.CS_BottomView_Height.constant = 330;           }           [self.bottomView setNeedsUpdateConstraints]; }

In this function, we only update the constant property of this height constraint according to the direction of the device.

If you run this instance, you will see the results you want.

End

From my own direct experience, what I have shown you in this tutorial is all the knowledge you need to get started with automatic layout, and of course, there are many other automatic layout features that are worth studying, such as "priority", automatic layout of the virtual format language and some of the more advanced applications of nslayoutconstraints. I might introduce them in a future post.

As always, please look forward and thank you for your reading.

Download Source *

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.