Что такое autolayout swift
Auto Layout Tutorial in iOS: Getting Started
In this Auto Layout tutorial, you’ll learn how to use constraints and apply them to making iOS apps.
Version
Making apps that look good in any orientation across multiple devices can be a challenge. If you’ve experienced this kind of frustration, despair no longer! Auto Layout makes it easy to support different screen sizes in your apps. In this Auto Layout tutorial, you’ll learn all about constraints and how to apply them.
For new iOS developers, here’s a quick overview of Auto Layout:
At first, Apple made one screen size for the iPhone. Developers didn’t have to create flexible interfaces as they only had to fit that one size. Today, differently sized devices and more emphasis on landscape mode demand user interfaces of different sizes. Auto Layout is Apple’s solution to this problem, enabling UI elements to grow, shrink and move depending on screen size.
Later in the tutorial, you’ll work on a project called Gallery Kit. To access the materials you’ll need, click the Download Materials button at the top or bottom of the tutorial. Before you get into the project, it’s important to get acquainted with Auto Layout.
Getting Oriented to Auto Layout
Before creating a user interface, take a tour of Xcode and Interface Builder. Interface Builder is a graphical tool inside Xcode that allows developers to create UIs using Auto Layout. Here are some of the common features you’ll come across when using Interface Builder:
A Simple Example
To start learning the ins and outs of Interface Builder, first create an empty iPhone application.
Open Xcode, select Create a new Xcode project and select the Single View App template.
Enter Buttons for the Product Name. Leave the other options as their defaults and go through the next steps to create the project.
Select Main.storyboard and then View Controller Scene in the Document Outline. Make sure to enable Use Auto Layout, Use Trait Variations and Use Safe Area Layout Guides in the Storyboard’s File inspector:
It’s time to get your hands dirty! The best way to get comfortable with Auto Layout is to create a user interface. Ready? Set? Go!
Dynamic Buttons
Click the Library button in the window bar. Find the Button row – it’s easier to search for the word ‘button’ to do this. Drag a button into the white rectangle representing your view controller in the main window area. Drag in a second button and position it below the first.
Now you’ll change the background colors of the buttons. Making sure the inspectors panel is open, click the Attributes inspector and find the Background option in the View section. Give the upper button a green background and the lower button a yellow background.
Select the green button and use the Add New Constraints menu on the bottom-right and enter 40 to make a 40-point constraint to its nearest bottom neighbor. Notice the red I-bar; clicking this will add or remove a constraint in that direction. Select Add 1 Constraint to actually create the constraint for the button. Now select the yellow button and enter 8 to make an 8-point constraint to the bottom of the view controller. Don’t forget to select Add 1 Constraint.
Open the Align menu with the yellow button selected and check Horizontally in Container, then click Add 1 Constraint. Now, select both buttons at the same time using the Shift key and, in the Align menu, check Leading Edges. Again, actually install the constraint by clicking Add 1 Constraint.
You might see a red circle with an arrow in it on the top-left. Usually, this indicates an issue that you need to fix. Don’t worry about this for now. You’ll fix it later. :]
Now you’ll see how this works at runtime. Add the following method to the class in ViewController.swift:
This toggles between a long title and a short title for the button that triggered the event. Connect this action method to both of the buttons in Interface Builder. Control-drag from each button to the view controller in the Document Outline and select buttonTapped: in the pop-up.
Build and run the app and tap the buttons to see how they behave. Perform the test in both portrait and landscape orientations.
Regardless of which button has the long or short title, the layout satisfies the constraints you have given it:
That is the entire specification for your user interface.
Time to Experiment
For fun, remove the Leading Alignment constraint. To do this, select it in the
Document Outline and press Delete on your keyboard. Then, select both buttons in Interface Builder and from the Align menu select the Trailing Edges option.
Now run the app again and notice the differences.
Now remove the Trailing Alignment constraint and, with both buttons selected, choose Align ‣ Horizontal Centers. That will center the top button with respect to the bottom button. Run the app and see how the buttons act when you tap them.
Sometimes the issue might be trickier to resolve. Select the Resolve Auto Layout Issues button all the way to the right to see a menu of options that can help by updating your existing constraints, adding missing constraints, resetting your constraints to constraints suggested by Xcode or clearing the constraints so that you can start over.
Using Intrinsic Content Size
The Add New Constraints menu has an Equal Widths option. If you set this constraint on two views, Auto Layout will make both views equally wide, based on which is the largest.
Select both buttons and choose Add New Constraints ‣ Equal Widths. This adds a new constraint to both buttons:
Even though there are two T-bars, in the Document Outline this shows up as a single Equal Widths constraint:
Run the app and tap the buttons. The buttons always have the same width, regardless of which has the largest label.
When both labels are short, the buttons will shrink equally. Unless a constraint prevents it, buttons will size themselves to fit their content. A button or label knows how wide and tall it is because it knows the length and font size of the text it displays or, in the case of a button, a combination of text with a background image and some padding. That’s the intrinsic content size, an important concept in Auto Layout.
You’ve already seen it in action with the buttons. Auto Layout asks your controls how big they need to be and lays out the screen based on that information. Usually, you want to use the intrinsic content size, but there are some cases where you may not want to do that. In these cases, you can set an explicit width or height constraint on a view.
Play around to get a feel for pinning and aligning views. Remember, you need enough constraints that Auto Layout can determine the position and size for all views.
Putting it Into Practice: Gallery Example
You should now understand constraints and how you can build your layouts by forging relationships between the different views. In the following sections, you’ll see how to use Auto Layout and constraints to create layouts that meet real-world scenarios.
Pretend you want to make an app that has a gallery of your favorite programmers. It looks like this in landscape and portrait:
The screen comprises four equal quarters. Each quarter has an image view and a label. How would you approach this?
If you haven’t already, download the Gallery Kit project using the Download Materials button at the top or bottom of this tutorial and open the starter project. The sample project includes the images you’ll need to display in the gallery.
Open Main.storyboard and select the iPhone SE size from the View As panel on the bottom-left.
From the Library, drag a plain View object onto the canvas. With the view selected, open the Size inspector and set the Width to 160 and Height to 284 points.
Next, in the Attributes inspector, set the view’s background color to green:
There are two reasons why you would drop a plain UIView onto a storyboard. First, you’re going to use it as a container for other views, which helps with organizing the content of your scenes. Secondly, it’s a placeholder for a custom view or control. In the second case, you’ll also set its Class attribute to the name of your own UIView or UIControl subclass.
Select the green view, open the Add New Constraints menu and uncheck Constrain to margins. Create four constraints to all four of the green view’s nearest neighbors in each direction by clicking the red I-bars:
This will create four new constraints between the green view and its superview, one for each side of the view. The actual spacing values may be different, depending on where you placed the view. You don’t have to change the values to match the ones above. Click Add 4 Constraints to finish.
Your storyboard should now look something like this:
The Safe Area
Are you wondering why the constraint at the top of the view stops at the status bar instead of going all the way up to the top of the screen?
Since iOS 7, the status bar is always on top of the view controller — it’s no longer a separate bar — so what gives? When you created the constraint, it didn’t attach to the top of the screen but the top of an invisible rectangle called the Safe Area.
The Safe Area is the part of the view controller that isn’t obscured by any bars like the status, navigation or tab bar. Because the navigation bar has a different height in landscape, the Safe Area resizes with the bar when the device is rotated. That makes it easy to place views relative to the navigation bar. The same goes for tab bars.
This view needs four constraints to keep it in place. Unlike a button or label, a plain UIView does not have an intrinsic content size. You must add constraints to determine the position and size of each view.
In this case, the size of the view is implied by the size of the superview. This layout has leading, trailing, top and bottom constraints, and these all have fixed lengths. You can see this in the Document Outline:
The width of the green view is calculated by the formula: width of safe area minus (80 + 80); and its height by the formula: height of safe area minus (13 + 163). The constraints are fixed, so the view has no choice but to resize. Again, your values may be different, depending on where you put the view.
When you rotate the app, the dimensions of the superview change, so the view’s size changes with it. Build and run the app, then rotate the simulator to see how the view behaves.
Fixed Sizes
You may not always want your view to resize when the device rotates, so you can use constraints to give the view a fixed width and/or height. Do that now.
Select the green view and click Add New Constraints. In the pop-up, select Width and give it a value of 160; then select Height and specify its value to be 372:
Click Add 2 Constraints to finish. You’ve added two new constraints to the view, a 160-point width constraint and a 372-point height constraint.
Also change the values in the existing constraints by selecting each one from the Document Outline and modifying their values in the Size inspector. Use these values: top: 13, leading: 80, trailing: 80, bottom: 163.
Run the app. Yep, it looks good in portrait.
Now rotate to see it in landscape. Whoops! Not only does it not look like you wanted, but the Xcode debug pane has dumped a nasty error message that looks like this at the top:
Remember when I said there must be enough constraints so that Auto Layout can calculate the positions and sizes of all the views? Well, this is an example where there are too many constraints. When you get the error “Unable to simultaneously satisfy constraints,” it means your constraints are in conflict.
To solve this, remove the Safe Area.trailing = View.trailing at the right and the Safe Area.bottom = View.bottom at the bottom by selecting them in the Document Outline and hitting delete.
The storyboard should look like this:
Now the view has the right number of constraints to determine its size and position. Run the app and verify that the error message is gone and that the view stays the same size after rotating.
Next, select the green view’s height constraint and, in the Size inspector, change its Constant to 284. This will make sure it’s half as large as the screen.
Painting the Portraits
From the Library, drag a Label onto the green view. Notice that now the guides appear within that green view because it’s the superview for the label.
Position the label against the bottom margin, spaced equally from the guides.
You now need to add a space constraint to anchor the label against the bottom, left and right of the green view, at 20 points distance. Ensuring that the label is selected, click the Add New Constraints button. Enter 20 for each of the bottom, left and right constraints, making sure the I-bar is solid, then select Add 3 Constraints:
Now, in the Attributes inspector, select Center Alignment.
It’s important to have a right and left constraint on UILabel s. Otherwise, they will show outside their superview when the text is too long.
Notice that these new constraints are listed under the green view’s own Constraints section, not in the main view.
Adding Images
From the Library, drag a new Image view object onto the storyboard and make the layout look like this:
The image view’s top, left, and right edges are pinned to its superview, but its bottom is connected to the top of the label with a standard spacing of 8 points. If you’re unsure of how to do this, then follow these steps.
1. Drag an Image view from the Library into the green view. Don’t worry about its size or position:
2. With the Image view selected, click Add New Constraints and choose the following options:
The top, left, and right I-bars are set to 20 points, but the bottom one is set to 8 points.
The constraints you chose result in a different frame than the image view’s current position and size. Interface Builder will automatically adjust the frame as it adds the constraints.
Now you’re ready to add images and names to your view. You’ll use the bundled images included in Assets.xcassets.
Still in Main.storyboard, select the Image view and, in the Attributes inspector, set Ray as the Image. Also set the Content Mode to Aspect Fit. Then, set the Background to White Color.
Double click the Label, and set its title to Ray.
Your layout should look like this:
Priorities
Notice that the constraints inside the green view turned red. This happened the moment you set the image on the image view. Why is your layout invalid? Take the guesswork out of it. Xcode will tell you what’s wrong.
Click the small red arrow next to View Controller Scene in the Document Outline to view the issues:
You have a Content Priority Ambiguity error. That’s a mouthful! Here’s what it means: If neither the image view nor the label has a fixed height, then Auto Layout doesn’t know by how much to scale each if the height of the green view should change.
Say at some point, the green view becomes 100 points taller. How should Auto Layout distribute these new 100 points among the label and the image view? Does the image view become 100 points taller while the label stays the same size? Or does the label become taller while the image view stays the same? Do they both get 50 points extra, or is it split 25/75, 40/60, or some other combination?
If you don’t solve this problem, Auto Layout has to guess, and the results may be unpredictable.
The solution is to change the Content Hugging Priority of the label. You can imagine hugging here to mean size-to-fit. In other words, the bounds of the view will hug the intrinsic content size. A higher value here means the view will be less likely to grow and more likely to stay the same.
Go into the Size inspector for the label and set the Vertical Content Hugging Priority to 252. That makes it one higher than the priority of the image view. As a result, when the superview changes size, the image view will be the one to resize, and the label will stay the same size.
The T-bars should turn blue again and the Auto Layout warnings should have disappeared.
Adding Other Heads
Drag the green view into the main view’s top-left corner. Recall that the green view had horizontal and vertical space constraints that determined its position in the parent view. It still has those, and they cause the frame of the view to be misaligned.
To fix this, use the Resolve Auto Layout Issues button and choose Update Constraints Constants. This will update the constraints to match the frame:
The leading constraint now has size of zero, represented by a thick blue line at the left edge of the window. Although the view sits in the corner, it needs constraints to anchor it there:
Now you are going to start adding more views to show more people. Select the green view and press Command-C followed by Command-V to duplicate it. Move the duplicate into the top-right corner:
Notice that the T-bars are red. When you made the duplicate, it lost its constraints for the X and Y position. To fix that, pin the view to the top and the right edges of the window. Make sure to uncheck Constrain to margins.
Duplicate two more times and put these copies in the bottom-left and bottom-right corners, respectively. The bottom-left view should have its leading and bottom pinned, while the bottom-right should have its trailing and bottom edges pinned to the superview.
Now it’s time to make the screen more colorful. Select each of the green views and change their backgrounds to a different color. Also change the label titles and the images view images to represent the programmers. In the end, your screen should look something like this:
Those are some good-looking programmers! :]
Run the app on the iPhone SE simulator. It looks good in portrait, but not in landscape:
It should be pretty obvious what went wrong: Because you set a fixed width and height on the four colored container views, they will always have those sizes, regardless of the size of their superview.
Select the fixed width and fixed height constraints from all four views and delete them. This is easiest in the Document Outline. If you run the app now, you’ll get something like this:
50:50 Split
To achieve your desired layout, you’re going to set each view’s width and height to be 50% of the ViewController’s view. In Document Outline, Control-drag from the green Ray view to the Safe Area view:
While pressing Shift, click Equal Widths and Equal Heights, and then press Enter. This allows you to select multiple items. Once those constraints are active, Ray will fill the screen, which is not the intention. :]
In the Size inspector, click Edit on the Equal Width to Safe Area row in the Sibling & Ancestor Constraints section:
In the multiplier field, enter 0.5 and press Enter. This will set the width of Ray’s view to be 50% of Ray’s container view. Repeat this for the Equal Height to Safe Area row. You should see that Ray is now the correct size:
Now repeat this for the remaining views. Build and run. Everything looks great!
Where to Go From Here?
Download the completed version of the project using the Download Materials button at the top or bottom of this tutorial.
Congratulations! Now you know what Auto Layout is all about, and you have some experience with the basics! There’s much more to learn. To keep learning, check out our Auto Layout tutorial video series.
If you have any questions or comments as you continue on your Auto Layout journey, join the forum discussion below.