(Translation) Start the Automatic Layout tutorial on iOS 7 (2), ios Layout

Source: Internet
Author: User

(Translation) Start the Automatic Layout tutorial on iOS 7 (2), ios Layout

The first half of this tutorial has been translated for a long time. I also learned the IOS Automatic Layout through this tutorial. However, the second half (that is, this article) has not been translated. Just recently, the translation of the chunk is coming to this tutorial for translation. The first half has been reposted to this blog, and the second half is the post. If you want to learn about the automatic layout of IOS, you can check it out. The automatic layout is very powerful.

This tutorial is definitely the best article to learn about IOS automatic layout.

Original article address: Beginning Auto Layout Tutorial in iOS 7: Part 2

The text is as follows:

Please note: team member Matthijs Hollemans (author of the IOS apprenticeship series) has transplanted this tutorial to iOS 7 feast. We hope you like it!

In the first iOS 7 Automatic Layout tutorial (1) you have seen that the old "struts-and-springs" model makes it easier for user interfaces to solve all layout problems. Automatic Layout is a solution, but it is also because it is powerful, so we need a little skill when using it.

Fortunately, Xcode5 makes automatic layout easier. If you tried Automatic Layout in Xcode4 and gave up, now we hope you can give it another chance. We will use it in Xcode5.

In the second and last sections of the Automatic Layout series, you will continue to learn all about constraints and how to apply them.

 

A journey of a thousand miles begins

This automatic layout tutorial starts with the very simple app below:
There are two buttons in the app with the background color set. You can see their border more clearly. There are some constraints between them. If you are learning the last part, you can continue to use your previous app, as long as you remove the other two buttons on the interface.

If you want to start again, use the Single View Application template to create a new iPhone Application. Drag two buttons to the scene and set the background color for them. Use the Editor \ Pin menu to create a Vertical Spacing constraint between two buttons, and then create a Bottom Space to Superview constraint (the size is 20 points) by clicking the next button ). Use the Editor \ Align menu to create a horizontal center constraint for the yellow button, and then two buttons align the left edges (alignment left edge ).

In Interface Builder, everything looks great. But let's see how they work. Add the following method to ViewController. m:

- (IBAction)buttonTapped:(UIButton *)sender{    if ([[sender titleForState:UIControlStateNormal] isEqualToString:@"X"]) {        [sender setTitle:@"A very long title for this button"                 forState:UIControlStateNormal];   } else {        [sender setTitle:@"X" forState:UIControlStateNormal];   }}

Set a click trigger event for both the long title and short title buttons. In Interface Builder, connect all buttons to the action method. Press ctrl to drag each button to view controller and select buttonTapped in the pop-up window.

Run the app and click the button to see how it changes. You can test both the horizontal and vertical screens.

Whether the button is a long title or a short title, the layout is always restricted by security:

  • The down button is always centered horizontally in the view.
  • The down button is always 20 points away from the bottom of the view.
  • The buttons on the top are always left aligned with the buttons on the bottom, and the distance between them is always 40 points.

The above three points are all the descriptions shown in your user interface.

Let's try to remove the left alignment constraint (select and press the Delete key in the outline window), select all buttons in Interface Builder, and select align right edge in the alignment menu. Run your app again to see the difference.

Next time, choose Align \ Horizontal Centers. It will make the two buttons always center and aligned. Run the app and click the button to see how the app runs. (Remember, if you see the orange dotted line rectangle when changing the constraint, you can use Editor \ Resolve Auto Layout Issuesmenu to update the button size and position .)

Processing width

One option in the Pin menu is Widths Equally. If you set this constraint in two views, the automatic layout will always make the width of all views equal to the width of the largest view. Let's try it.

Select All buttons and select Editor \ Pin \ Widths Equally. This adds a new constraint to all buttons:

Before that, you can take a look at the content about the constraint type in the first part of the tutorial. It looks like a T-frame, but there is a circle in the middle that says "=.

Of course, there may be two TBS. A separate Equal Widths constraint is shown in the Outline document:

Change the label text on the button, and the size of both buttons will change at the same time. Change the label text of the following button to "X ". At this time, you will find that the above button cannot match its text:

How does the Automatic Layout know the width of the button used? If you pay attention to it, you may notice that the size of the button above is no longer correct:

Obviously this is not the effect you want. Select the above button and select Size to Fit Content from the Editor menu (or use the shortcut key limit = ). Now, the text matches the button again, and the yellow button also changes the size due to the Equal Widths constraint.

Run the app and click the button. The button is always the same width, no matter which label is bigger:

Of course, if the labels are very short, the buttons will be scaled out in width. Unless there are other constraints that prevent them, the button size will match their titles precisely, not much, not much. What do we call this situation? Yes, it is the inherent content size.

Inherent content size

Before automatic layout, you always need to tell the button and other controls how big they should be, then set their frame or bounds, or restore their size in Interface Builder. But now the situation has changed. Most controls can determine how wide they need based on the content. The label can know how wide it is and how high it is, because it knows the length of the text and the size of the text. The buttons are the same. You can determine the size based on the text, background image, and padding. Similarly, this is also effective for segmented controls, SS bars, and most other controls, but some of them may only predict the height but cannot know its width. This feature is called the inherent content size, which is an important concept for automatic layout. You have seen the button action. The automatic layout will ask you how much your control needs and draw the control on the screen based on the information. In general, you will use the inherent content size, but you may not want to use it in some special cases. Then you can set an accurate Width and Height constraint for the control to prevent the use of the inherent size. Imagine that you have set an image on UIImageView. If the image size exceeds the screen size, what will happen? You can give the image view a fixed width and zoom ratio unless you want to redefine the image size.

What will happen if you give the button a fixed width constraint? The button will calculate its own size, but if you give it a fixed size, it will not be calculated. Select the top button and select the Pin \ Widthfrom menu. Add a fixed width to the button (a complete tfont frame is displayed below the button ):

This type of constraint only applies to the button itself and does not apply to its parent view. Therefore, in the Outline document, it will be listed under the button object, you can set the width of the button to 46.

You cannot simply stretch the button to adjust the size. If you do, you will only get an orange dotted box. Remember that constraints are not automatically updated in Xcode5 (unlike Xcode4 ). Therefore, if you change the size and position of the button, it will prompt you to make the constraint match again. This is an alternative to simply changing constraints.

Select the Width constraint and go to the Attributes inspector tab. Change the width constraint of the button to 80:

Run the app and click the button. What happened? The text of the button is changed, but it is deleted because there is not enough space in the button:

Because the buttons on the top have a fixed-width constraint, and all buttons require the same size, they will never contract or expand.

Note: You may not want to set the Width constraint for the button in the design. The best way is to make the button use the inherent size, but if you want to change the widget size when the app is running, but it cannot. You should check whether there are any fixed Width size constraints.

Play around with this stuff for a bit to get the hang of pinning and aligning views. Get a feel for it (this sentence cannot be translated and can be solved by yourself ~) Not everything can be immediately apparent. You only need to remember that there must be enough constraints for automatic layout to pre-calculate the positions and sizes of all views.

Gallery example

Now you may want to decide what the constraint is. How can you build your own layout by establishing relationships between different views. In the following section, you will see how to use automatic layout and constraints to create a layout that conforms to real-world scenarios.

Let's pretend that you want to create a program to browse your images. It looks like the following in landscape and landscape:

The screen is divided into four parts, each of which has an image view and a label. How can we achieve this effect?

Let's start creating this app. First, use the Single View Application template to create a new iphone project named "Gallery ".

Open Main. storyboard. Drag the View from the Object Library to the View. Set the size to 160 and 284, and change its background color to a color other than white (for example, green ):

Note: There are two reasons to drag the UIView to the story board: a) You need to use it to include other control views, which can help you organize the scene content; B) it is also used as a placeholder for a custom view or controller. You can set its Class attribute, change it to your custom UIView/UIControl class (that is, the class that inherits UIView/UICtontrol ).

Let's give these views some constraints. You have seen two ways to add constraints: Use the Editor \ Pin and Align menus, and hold down ctrl to drag the two views. Here is the third method to add constraints. At the bottom of the Interface Builder window, there is a button like this:

The four buttons surrounded by an ellipse are used for automatic layout. From left to right are: for its (Align), fixed (Pin), solve the Automatic Layout Problem (Resolve Auto Layout Issues) and redefinition of the size (Resizing Behavior ). The corresponding items in the top three button fish Editor Menus have the same function. The Resizing Behavior button allows you to change the added constraints when resetting the view size.

Select a green view and click the Pin button. A series of constraints that you can add will pop up:

 

The Spacing to nearest neighbor on the top is the most frequently used. Click the four character frames, and they will become the red of the object:

In this way, four new constraints will be created for the green view and its parent view. The actual spacing value varies from person to person, depending on the position of your view. (You don't need to change these values to match my graph ). Click Add 4 Constraints to Add the constraint.

Now your storyboard looks like this:

The view requires these four constraints to ensure its position. Unlike buttons or labels, UIView has no inherent content size. You must have enough constraints to ensure the position and size of each view. The view always needs constraints to tell it the size of the view.

You may wonder where the size constraint is? In this case, the size constraint of the view is hidden in the size of the parent view. There are two Horizontal Spaces constraints and two Vertical Spaces constraints in the layout to ensure a fixed length. You can see them in the Outline document:

The width of the green view is calculated by this formula: "The width of the parent view-(98 + 62)". Its height is: "Parent view height-(65 + 199 )". In this way, the spacing is fixed, and your view does not have to be customized. (Your values may be different based on the position of your view ).

When you rotate this app, the size of the parent view changes from 320X568 to 568X320. The formula recalculates the width and height, and then you get the new Green view Size (408X56 ).

You can rotate your own images and try it. You can also simulate them intuitively in Interface Builder. Open the Assistant editor (press the button in the Xcode toolbar that looks like an alien/Butler) and select Preview in the pop-up menu:

Click the arrow at the bottom to change the interface direction. In this way, you can immediately preview the horizontal layout of the story board. Green view will redefine the size to meet the horizontal and vertical spacing constraints.

You can leave this preview window, which automatically changes when you design the UI. You can also switch between the 3.5-inch and 4-inch screens.

Note: You may wonder why the top constraint is not at the top of the screen:

It stops at the status bar. This is because in ios7, the status bar is always drawn at the top of the view Controller-instead of a separate bar. What is the purpose of this operation? When you create a constraint, it cannot be exactly attached to the Top of the screen, but there is an invisible row on the Top, which is called Top Layout Guide.

In a normal view Controller, this guide is 20 points away from the top, at least when the status bar is not hidden. In the navigation controller, It is located under the navigation bar. Because the navigation bar has different heights in the view, the Top Layout Guide will move along with the navigation bar when the device rotates. In this way, you can easily obtain the relative position of the view and navigation bar. Similarly, there is a Bottom Layout Guide at the Bottom to place the label bar and toolbar.

Sometimes, you may not want to reset the size of your UIView when the device rotates, so you can assign a fixed width and height constraint to this view. Now, let's try it. Select a green view and click the Pin button. In the displayed window, check width and height.

Click Add 2 Constraints to Add the constraint. Now you have added two new constraints to the view: one is the 160-point width constraint and the other is the 284-point height constraint:

Because the width and height are only applied to the current view, they are located under their own view in the Outline document. In general, constraints all express a certain relationship between two different views-for example, Horizontal and Vertical Space) the constraint is the relationship between the green view and its parent view-you can also think that the width and height constraints are green view and its own constraints.

Run the app. Oh, how nice it looks. Now, place your screen sideways! Instead of changing the view size as you would like-the view size should be changed again-but an error is reported. Xcode provides a bunch of error messages:

Gallery[39367:a0b] Unable to simultaneously satisfy constraints.Probably at least one of the constraints in the following list is one you don't want. Try this: 
     (1) look at each constraint and try to figure out which you don't expect; (2) find the code that
     added the unwanted constraint or constraints and fix it. (Note: If you're seeing
     NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for
     the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSLayoutConstraint:0xc1a1e80 V:[UIView:0xc1a2b10(284)]>", "<NSLayoutConstraint:0xc1a36c0 V:[_UILayoutGuide:0xc1a2d20]-(65)-[UIView:0xc1a2b10]>", "<NSLayoutConstraint:0xc1a36f0 V:[UIView:0xc1a2b10]-(199)-[_UILayoutGuide:0xc1a3230]>", "<_UILayoutSupportConstraint:0xc15dbd0 V:[_UILayoutGuide:0xc1a2d20(20)]>", "<_UILayoutSupportConstraint:0xc1a1510 V:|-(0)-[_UILayoutGuide:0xc1a2d20] (Names: '|':UIView:0xc1a2930 )>", "<_UILayoutSupportConstraint:0xc1a3720 V:[_UILayoutGuide:0xc1a3230(0)]>", "<_UILayoutSupportConstraint:0xc1a30e0 _UILayoutGuide:0xc1a3230.bottom == UIView:0xc1a2930.bottom>", "<NSAutoresizingMaskLayoutConstraint:0x8c6c6a0 h=--& v=--& H:[UIView:0xc1a2930(320)]>") Will attempt to recover by breaking constraint <NSLayoutConstraint:0xc1a1e80 V:[UIView:0xc1a2b10(284)]> Break on objc_exception_throw to catch this in the debugger.The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. . . .

Do you still remember saying "You must have enough constraints to calculate the positions and sizes of all views only after automatic layout? Well, in this example, there are too many constraints. When you see the error "cannot satisfy all constraints at the same time (Unable to simultaneously satisfy constraints)", it means that there is a conflict between your constraints.

Let's look at the constraints:

The green view has six constraints, four spacing constraints (1-4), and the width and height constraints (5 and 6) You just set ). Where is the conflict?

The problem should not be solved when the screen is portrait, because it is satisfying in mathematics. The width of the parent view is 320 points. If you have added the Horizontal Space and Width constraints, you should ensure that their total length is less than or equal to 320 points. This is how I calculate the view position: 98 + 160 + 62 = 320. Similarly, all vertical constraints should be 568 points after they are added.

However, when you rotate the device to a horizontal screen, the window (the parent view) becomes 568 points wide. This means 98 + 160 + 62 +? = 568. There are an additional 248 points, which cannot satisfy the equation. Therefore, the automatic layout does not know where to get the 248 points. Likewise, vertical constraints are the same.

There are two ways to solve the conflict: first, keep the view width fixed, but the outer margin must be variable. The second is to keep the outer margin fixed, but the width must be variable. You cannot fix them at the same time. Remove one of these constraints. In the above example, if you want to have the same width in both the landscape and landscape screens, Horizontal Space must be removed.

Remove the horizontal and vertical Spacing on the right. The following figure is displayed on the story board:

Now, view has a correct constraint to predict its size and position-not many, not many. Run the app to check whether the error message is missing and whether the view can maintain the width after rotation.

Note: Although Interface Builder can warn you of invalid constraints, it is not a god. It will only warn you: Oh, you are not bound enough. However, if you have too many constraints, it cannot be detected. However, at least when an error occurs, the automatic layout still provides a detailed error message. If you want to learn

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.