Start the automatic layout tutorial in iOS 7 (i)

Source: Internet
Author: User
Tags dashed line delete key

Have you ever wanted your app to look good and frustrated in the direction of the screen? Are you near incontinence when it comes to supporting the iphone and ipad screen layout interface? Today I will bring you good news! It is not difficult to design a user interface for a screen of the same size, but if the size of the screen changes, the position and size of the UI elements also need to be changed accordingly. So far, if your design is quite complex, you have to write a lot of code to fit the layout. You should be glad that this is not the case anymore.--IOS6 offers an excellent new feature for the iphone and ipad: Automatic layout. The automatic layout has been improved in Xcode 5 and iOS7! If you've ever tried to use auto-layout in Xcode4 and eventually give up, it's time to give Xcode5 a chance. In your program, the automatic layout not only makes it easy to support screens of different sizes, an additional feature, it also allows localization to become almost insignificant. You no longer need to create new nibs or storyboards for each of the languages you want to support, including right-to-left languages like Hebrew or Arabic. This tutorial will show you how to start an automatic layout using Interface Builder. In the IOS6 tutorial, we discussed this tutorial further, and then we have a new chapter based on this knowledge point, and show you how to fully release the energy of automatic layout through code. Note: We have started to update the corresponding chapters in the IOS6 tutorial to ios7-This is just the first to Jiechan! When we are done, all subscribers to the IOS6 PDF tutorial will receive a free update download. So, prepare snacks and your favorite coffee, ready to become the auto layout of the talent bar! problems with springs and strutsYou must be familiar with autosizing masks-is also considered springs&struts mode. Autosizing mask determines what changes should be made to the parent view of a view when its size changes. Does it have a flexible or fixed invariant margins (struts)? What changes does it make (springs)? For example, a flexible-width view, if its parent view border, will also be widened accordingly. With a fixed margin on the right side of a view, its right edge will always stick to the right edge of its parent view. The autosizing system works very well in simple cases, but when your layout becomes more complex, it immediately kneels. Let's look at an example that springs and struts cannot handle. Open Xcode5 and create an iphone project based on the single View application template. Called "Strutsproblem": Click Main.storyboard. Before you do anything else, turn off the storyboard auto-layout first. You need to tabs the sixth of the first option in File Inspector: Remove the box with use AutoLayout. Now storyboard use the old struts-and-springs model.Note: If you use Xcode4.5 or later, the nib or storyboard files are enabled by default for automatic layout. Because automatic layout is a new feature of iOS6 and above, if you want to develop compatible IOS5 programs with the latest Xcode, you need to remove this option. Drag three new views to the main view and arrange them like this: to make it clearer, give each view a color so you can tell which is the donkey and which is the horse. The distance from each view to the window is 20 points, and the distance between the views is 20 points. Inset The width of the bottom view is 280 points, and the width of the above two views is 130 points.  The height of all views is 254. Run the program on the iphone Retina 4-inch Simulator and rotate the emulator to landscape. The program looks like a ghost, which is not what I imagined: Note: You can use the hardware\rotate left and Rotate right menu options to rotate the emulator, or press ← or → by pressing the?  key on the keyboard.   and you imagine the program in landscape should be like this obviously, three views of the autosizing masks left a few areas to improve. Change the autosizing setting of the upper left view to this: this will attach the view to the top left edge (not the lower right edge) and resize itself horizontally and vertically when the parent view size changes.   Similarly, the autosizing setting in the upper-right view is changed to this: it's close, but not exactly the same. The padding between views is incorrect. In other words, the size of the view is not exactly correct. The problem is that when the parent view changes size, autosizing masks tells the child view to resize, but does not tell the child view how much to adjust (pit?). )。   You can flirt with autosizing masks-For example, change the flexible width and height settings (springs)-You won't get exactly the right three-spaced 20-point view. To address the layout of this springs and struts approach, unfortunately, you need to write some extra code.   before, during, and after the user interface is rotated, Uikit sends some messages to your view controller, and you can intercept the messages to make changes to your UI. Representative like Viewwilllayoutsubviews, you will rewrite this method to change any frame that needs to rearrange the view.   Before you do this, you need to make a outlet property to refer to this view.   Switch to Assistant editor mode, hold down CTRL and drag all three views into the VIEWCONTROLLER.M: When the view controller is rotated to a new direction, the callback will be called. It monitors the direction of the view controller rotation and adjusts the view size appropriately-in this case, there will be a hard-code (a method called Hard-code) offset with a fixed value instead of a variable variable, depending on the known iphone screen size. This callback occurs in an animated block, so it changes size dynamically.   Don't run this program yet. First you need to resave the autosizing masks of three views as follows, otherwise autosizing mechanism will conflict with the location and size you set in Viewwilllayoutsubviews. So you can run the program and flip it to landscape. The view is now arranged in the very number. Flipped back to portrait, verified that everything was fine.   It works, but you need to write a lot of layout code for this very simple example. Imagine that the effort to pay for the layout is very complex, especiallyIs the size of the individual view's dynamic change, or the number of child views is not fixed.   Now try to run the program on a 3.5-inch simulator. I got a go. The location and size of the view is wrong again, because Viewwilllayoutsubviews's hard-code coordinates are based on a 4-inch-size phone (320x568 replaces 320x480). You can add another if statement to determine the screen size and use a different set of coordinates, but you can see that this method quickly becomes impractical.   Note: Another way you can do this is to create separate nibs for the portrait and landscape modes. When the device rotates, you load the view from another nib and replace the current one. However, this requires a lot of work, and maintaining two nibs will also increase the problem. This approach also becomes impractical when you use storyboards instead of nibs. Automatic layout Save the Ape! Now you will see how to use automatic layout to achieve the same effect, remove viewwilllayoutsubviews from VIEWCONTROLLER.M, because we no longer need to write any code. Select Main.storyboard and select Open Use AutoLayout in File Inspector: Run the program and rotate to landscape. Now it looks like this: Let's put the automatic layout into action. When you click on the top two views, press and hold the button so that two views are selected. Select Pin\widths equally from the editor menu of Xcode: Select the two same views again, and choose Editor\pin\horizontal Spacing. (although after you've done the first pin processing, two views still appear to be selected, they're only in a particular layout relationship display model.) So you need to re-select both views) Storyboard now looks like this: an orange "T-bar" shape represents a constraint between views. So far you've added two constraints: One equal-width constraint and one horizontal constraint that sits between two views. Constraints express the relationships between views, and they are the most important tools you use to create layouts using automatic layouts. The goods look a little scary, but once you understand what it means, it becomes quite simple. To continue the layout for this screen resume, perform the following steps. Add more orange T-bars to each step.o Top Space to Superview o leading Space to Superview For the view in the right, choose:o Top Space to Superview o Trailing Space to Superview And for the big view at the bottom:o leading Space to Superview o Trailing Space to Superview o Bottom Space to Superview Now you should have the following constraints: Note that the t-bars is still orange. This means that your layout is not complete; auto layout does not have enough constraints to calculate the position and size of the view. The solution is to add more restraint until they turn blue. Press down? Key and select three views. From the Editor menu, select Pin\heights equally. Now select the view in the upper-left corner and the bottom view (press the same as before). Key), select Editor\pin\vertical Spacing. Interface Builder should look like this: T-bars has turned blue. The automatic layout now has enough information to calculate a valid layout. This looks a bit disorganized, because the equal width and the high constraints take up a lot of space. Run the program and ... I said, no need to write a line of code to run very well. No matter which simulator you run on, the layout works well on 3.5-inch and 4-inch devices. It's pretty cool, but what the hell are you doing here? Automatic layout lets you express the relationship between the view in the layout and every other view, rather than requiring you to point out how large the view is and where it is placed. You need to place these relationships (what we call constraints) into the layout: 1. The upper-left and upper-right views always have equal widths (that is, the first widths equally command in a pin). 2. The horizontal orientation of the view in the upper-left and upper-right corner is 20 points away (that is, the horizontal spacing in the pin). 3. All views always have the same height (that is, the Heights equally command in the pin). 4. The above two views and the following view have a 20-point distance (that is, the vertical spacing in the pin) in the vertical direction. 5. The view and screen edges have 20 points (top,bottom,leading and trailing space constraints relative to the parent view). These are enough to show how the automatic layout should be placed and how the view should be handled when the screen size changes.
You can see all of your constraints in the left document outline, which is called constraints (which is added when you activate automatic layout for storyboard). If you click on a constraint in document outline, Interface Builder will highlight it in the view: The constraint is a real object (Nslayoutconstraint), and they also have attributes. For example, select the spacing constraint for the above two views (called "Horizontal Space (20)") and switch to attributes Inspector. You can change the size of the edge space by editing the constant field there. Automatic layouts are more expressive than springs and struts on the description view. In the remainder of this tutorial, you will learn all about constraints and how to apply them to interface Builder to construct different kinds of layouts. how automatic Layout worksAs you can see in the test sample above, the most basic tool for automatic layout is constraints. A constraint describes the relations between the two views. For example, you might have a constraint: "The right edge of label A and the left edge of Button B have a 20-point white space." Automatic layout takes all constraints into account, and then calculates the ideal position and size for your view. You no longer need to personally set frames for your view-the automatic layout will do the work for you entirely based on the constraints you set for these views. Auto layout Previously, you always had to set hard-code for the view's frames, either in interface Builder to place them in a specific coordinate, or by passing a rectangle to initWithFrame:, or by setting the frame of the view , bounds, or the center property. In the case of the program you just made, you need to explicitly set frames as: You also need to set the auto-sizing masks for these views: this is no longer what you need to consider for screen design. With automatic layout, you need to do this: the size and position of the view are no longer important, only the constraints matter. Of course, when you drag a new button or label onto the canvas, it will be a certain size, and you'll drag it to a location, but it's just a design tool to tell interface Builder how to place the constraint. think what you want, as you wish.The biggest advantage of using constraints is that you no longer have to waste your time on coordinates. Instead, you can describe how views are associated with other views in an automatic layout, and automatic layout will do all the hard work for you. This is called design based on purpose (designing by intent). When you design for a purpose, you express what you want to achieve without worrying about how it will be achieved. The upper-left coordinate of the button is (20,230), and now you can say that the button is centered vertically on its parent view and has a fixed distance relative to the left edge of the parent view. Using this description, no matter how large or small the parent view, automatic layout can automatically calculate where your button needs to appear, and other examples designed for the purpose (automatic layout can handle all these instructions): "The size of the two text fields needs to be equal." "These two buttons need to be moved together all the time. "These four labels need to be right-aligned all the time. "This makes the settings of your user interface more descriptive. You simply define the constraints and the system automatically calculates the frames for you. In the first part you see that even for a few views the right layout in both directions requires a lot of work. With automatic layout, you can get around these troubles. If you set the constraint correctly, the layout will not need to be changed in the direction of the vertical and horizontal screen. Another important benefit of using automatic layout is localization. For example, the text in German, the name is longer than the grandmother's binding cloth, suitable for matching up is a very troublesome thing. Again, the automatic layout saves the ape, because it automatically changes the size of the label according to what the label needs to display. Now add German, French or any other language, just set the constraint, then translate the text, then ... No, then! The best way to get automatic layout tips is to use it, so that's what you'll learn in the rest of the tutorial. Note: Automatic layout not only works on rotation, it also scales your UI easily to fit different sizes of screens. It's not a coincidence that when IPhone5 has a higher screen, this technology is added to iOS as well! The automatic layout can easily stretch the user interface of your program, thus filling up the extra space in the vertical direction of the iPhone5. With the dynamic type in iOS7, automatic layout becomes more important. Users can now change the global font size setting--with automatic layout, this will be very simple. hug constraint (courting constraints)Close your current project and create a new iphone project with a single View application template. Called "Constraints". Any project created with XCODE5 will automatically assume you will use automatic layout, so you don't need to do anything extra. Click Main.storyboard to open Interface Builder. Drag a new button onto the canvas. Note that when you drag and drop, the blue dashed line will appear. This writing line is used as a guide. At the edge of the screen and at the center, there will be a wire: If you've used interface Builder before, you've definitely seen these wizard lines. This is a great help to our alignment controls. When automatic layout is activated in Xcode4, there is another purpose for the wire. You can still use them to align, but they will also tell you where the new constraints will be. If you drag the button in the opposite direction of the wire to the upper-left corner, the storyboard in Xcode4 looks like this: There are two Blue objects attached to the button. These T-bar-shaped objects are constrained. Regardless of where you put the UI controller in the interface builder of Xcode 4, it always gives you a valid constraint. This sounds a good idea in theory, but in practice it is very difficult to use automatic layout in Interface Builder. Fortunately, there has been some improvement in the XCODE5. Drag the button onto the canvas and see nothing of the t-bars shape: It is also useless in the Document Outline Panel constraints section. Get the conclusion that no constraints are set on the button at this time. So how does this work? The automatic layout we knew before always required enough constraints to determine the size and position of the view, but now we have no constraint here. Are you sure this is a complete layout? This is the biggest boost for XCODE5 relative Xcode4: No more forcing you to always have an effective layout. Note: 1. It is unwise to run a program with an invalid layout because the automatic layout does not correctly calculate where the view needs to be placed. Either the location of the view is unpredictable (constrained enough), or the program crashes (too many constraints).  2.xcode4 tries to ensure that there is always enough correct constraints to create a valid layout. Unfortunately, it often replaces your constraints with what you don't want. This can be frustrating, for this reason many developers have abandoned automatic layouts.  in 3.xcode5, when you edit storyboard it allows you to have an incomplete layout, but it also points out which areas you need to modify. Automatic layout-driven user interface created with Interface Builder is more interesting and consumes less time with XCODE5。 If you don't provide any constraints at all, Xcode automatically assigns a default set of constraints, which is what we know about automatic constraints. It will do this in the compile time of the program built, not the design time. When you design your user interface, the automatic layout in XCODE5 to work hard to not participate in your design approach, which is why we like it. Automatic constraints provide a fixed size and position for your view. In other words, the view always has the same coordinates you see in storyboard. This is very handy, because that means you can ignore the automatic layout a lot. You can add constraints to those controls that have sufficient constraints, and only create constraints for those views that require special rules. OK, let's play with the constraints and see what they can do. Now, the button is in the upper-left corner, and there is no constraint. Confirm that the button is aligned to the wire with two corners. Use the Editor\pin menu to add two new constraints to the button, which looks like this: There are currently two constraints, one is the horizontal space constraint on the left edge of the button and the main view, the button and the main The vertical space constraint on the top edge of the view. This relationship is described by a constraint: "The button is always located at the upper-left corner of its parent view at 20 points." "Note: These are actually not very useful constraints because they have the same automatic constraints. If you always want your button to be relative to the upper-left corner of the parent view, then you might as well not provide any constraints for Xcode to do this for you. Now drag the button and place it in the upper-right corner of the screen again and align the blue to the wire: when it comes to automatic layout, orange stands for bad. Interface Builder draws two orange squares: one is a dashed border, and the other is a solid line border. A dashed block is a frame that displays a view based on an automatic layout. A solid block is a frame based on the view you place on the screen. These two should match, but not here. How you modify it depends on what you want to achieve: 1. Do you want the button to be attached to the left edge of the screen at 254 points? In this case you need to make the existing horizontal space constraint larger by 234 points. This is exactly the meaning of "+234" in orange Badge. 2. Do you want to have the button attached to the right edge of the screen? Then you need to remove the existing constraint and recreate the new one. Delete the horizontal space constraint. First, select it in the canvas or document outline, and then press the DELETE key on your keyboard. Note:You may wonder why Xcode does not automatically add a constraint for the x-axis direction. The rules in Xcode are: Xcode creates automatic constraints only for objects that you don't have any constraints on. Once you add a constraint, you are telling Xcode that you took over the view. Xcode will no longer add any automatic constraints, and want you to add the required constraints for this view.   Select the button and choose editor\pin| Trailing Space to Superview. This forces a new constraint on the right edge of the button and on the right edge of the screen. The relationship is expressed as follows: "The button is always at 20 points from the upper-right corner of its parent view. "  Run the program and rotate it to landscape. Note how the button maintains the same distance from the right edge of the screen: When you place a button (or any other view) that is aligned to the wire, and create a new constraint, you get a "HIG" (Apple's IOS Human Interface guidelines Document) defines the standard size of the interval constraint. For borders, the standard size space is 20 points.   Now drag the button to the left: that's what you mean---this button should always be centered at the bottom. Notice that you don't have to tell the Interface Builder button what the coordinates are, unless you want to pin it on the view.    with automatic layout, you no longer have to worry about the exact coordinates or view size of the view position. Instead, the automatic layout gets both parameters based on the constraints you set.   You can see this classic transfer in the button's size inspector, and now there's a big difference: if you don't use automatic layout, entering a value into the X,y,width or height field will change the position and size of the selected view. With automatic layout, you can still enter new values into these fields, but if you have already set constraints on the view, this can cause the view to be misaligned. You will have to update the constraint to match the new value.   For example, to change the width of a button to 100, the canvas would look like this: Xcode4 replaces the center X alignment constraint with horizontal space, and a new constraint on the button forces it to be 100 wide Points However, Xcode5 says, "It doesn't matter to me if you want the button width to be points, but you have to know that the constraints don't."   In this case you want the button to be 100 points wide. There is a special constraint type for this: the Fixed width constraint. First clickUndo, so the button is centered again, and the T-bars is blue. Select the button and select Editor\pin\width. This places a new T-bar under the button: Unlike other constraints, the width constraint is applied only to the button itself, between the button and its parent view. You can think of this as a constraint between the button itself and itself.   You may wonder why the button did not have a width constraint before. Why does automatic layout know how wide the button is?   The thing is this: button himself is aware of how wide he is. It is based on its own title text plus some padding on the line. If you set a background picture for the button, it will also take into account.   This is exactly what we are familiar with intrinsic content size. Not all controllers have this, but most of them are (Uilabel is an example). If a view can calculate its ideal size, then you don't need to specify the width or height constraint specifically for it, and you'll see more about it later. To restore the button to its optimal size, we first need to remove the width constraint. Then select the button and choose Size to Fit Content from the editor menu. This allows you to restore the intrinsic content size of the button.  TangoWizard lines not only appear between a view and its parent view, but also appear between views at the same level. Drag a new button onto the canvas for a demonstration. If you drag the button close to other objects, their wizard lines will start interacting with each other.   Put the new button on the back of the previous button intact: It is orange, which means that the button requires at least another constraint. The size of the button is known (using intrinsic content size), and there is a button constraint on the x-axis. Only the y-axis is left without constraints.   This lack of constraint is easy to determine, but the more complex design may not be so obvious. Fortunately, you no longer need instead focusing, Xcode has recorded and can tell you exactly what is missing.   There will be a small red arrow in document Outline, right behind the view Controller scene. Click this arrow to see all auto layout issues: This pop-up menu has different options. The options for this menu are context-based-what views you drag and drop and the direction your mouse moves. Select Bottom Space to Bottom Layout.   Now the New button has a vertical space at the bottom of the screen and a horizontal space associated with the other button. Although the space is very small (only 8 points), T-bar may not be easy to see, but it is there.   Click Horizontal Space (8) in document Outline: Set a green background color for the new button, which makes it easier to see its scope.   Because you align the two buttons together, there are now 8 points intervals between them that are recommended by HIG. CTRL + drag between two buttons to change this to a constraint. Select Vertical Spacing from the pop-up menu.  note: "HIG" is the abbreviation for "IOS Human Interface Guidelines" and contains a good user interface design recommended by Apple. It is necessary for any iOS developer to read this specification. Hig explains which UI elements are suitable for use and how best to use them. You can find it here. (https://developer.apple.com/library/ios/DOCUMENTATION/UserExperience/Conceptual/MobileHIG/introduction/introduction.html)   However you are not limited to the standard interval between controls. Constraints are mature objects, just like views, so you can change their properties.   Select the vertical space constraint between the two buttons. You can click on the T-bar on the canvas, although this is a bit cumbersome. The simplest way to do this is to choose a constraint in document outline. Once you have checked the constraints, then switching to attributes Inspector:button will certainly keep them in the vertical direction, but not horizontally! The reason is obvious: the green button does not have an x-axis direction constraint.   Adding a horizontal space to the left edge of the screen for the green button does not solve the problem. This constraint only causes the green button to always remain in the same x-axis coordinates, even in landscape mode. It doesn't look very good, so you need to say the same thing: "The yellow button will always be centered horizontally, and the left edge of the blue button will always be aligned with the left edge of the yellow button." "  You have created a constraint for the first case, but the second one is not. Interface Builder Displays the wizard line for alignment so you can drag the button above until it snaps to the left edge of the yellow: 

Start Automatic Layout in iOS 7 tutorial (i)

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.