iOS

Introduction to Auto Layout


Editor’s note: If you’ve downloaded the Xcode 6 beta and played around with it, one thing you may notice is the change of Interface Builder. The default view controller is now wider and doesn’t look like an iPhone 5. When you position a button in the center of the view and run the app, it doesn’t look good. The button is not centered properly.

What’s wrong? How can you make it right? The answer is Auto Layout. Auto Layout is a constraint-based layout system. It allows developers to create an adaptive interface that responds appropriately to changes in screen size and device orientation. We seldom talk about Auto Layout in our tutorials. Some beginners find it hard to learn and avoid using it. Starting from Xcode 6, you should learn to love Auto Layout. Apple is expected to release 4.7-inch and 5.5-inch iPhone 6 this fall. Without using Auto Layout, it would be very hard for you to build an app that supports all screen sizes.

auto-layout-featured

So starting from this week, we’ll publish a series of articles about Auto Layout. We’ll start with the basics.

Enter the introduction of Auto Layout by Ziad.

I know that there are many developers who hates Auto Layout, maybe because it’s relatively new or it’s hard to use for the very first time. But believe me, once you get comfortable with it, it becomes one of your greatest tools that you can’t live without when developing your app. In this tutorial, I will give you a very brief introduction of Auto Layout.

Why Auto Layout?

Auto Layout is a way that lets developers create user interface by defining relationships between elements. It provides a flexible and powerful system that describes how views and the UI controls relate to each other. By using Auto Layout, you can get an incredible control over layout, with a wide range of customization, and yield the perfect interface.

Auto Layout is a fantastic tool. It does things that earlier technologies could never dream of. From the edge case handling of creation of reciprocal relationships between views, Auto Layout introduces immense power. What’s more, Auto Layout is compatible with many of Apple’s most exciting application programming interfaces (APIs), including animations, motion effects, and sprites.

Okay, let me give you an example and hopefully you’ll have a better idea why Auto Layout is needed. In Storyboard, you place a button right in the center of the view. Run the app on both iPhone Retina (3.5-inch) and iPhone Retina (4-inch) simulators.

Auto Layout - Button not centered

You’ll end up with the above results and it turns out that the button isn’t centered when running on a 3.5-inch device.

Why? What’s wrong with it?

Without using Auto Layout, the UI controls (e.g. button) we layout in the Storyboard is of fixed position. In other words, we “hard-code” the frame origin of the control. For example, the “Press Me” button’s frame origin is set to (104, 255). Therefore, whether you’re using a 3.5-inch or 4-inch device, iOS will draw the label in the specified position. This explains why the “Press Me” button was not displayed properly on a 3.5-inch iPhone, for which the screen height is different.

Obviously, we want to the app look good on both 3.5-inch and 4-inch iPhone. And this is why we need Auto Layout.

How To Use Auto Layout in Interface Builder

Before we show you how to fix the alignment issue in the example, let’s have a brief walkthrough of the Interface Builder and get to know how Auto Layout can be applied.

First, set up a new project based on the Single View Application iOS app template. In the project options, choose iPhone for the device family, save the project, then open the Storyboard. You will notice a menu at the bottom-right corner. The buttons in the menu are related to Auto Layout. You can use for alignment, sizing, spacing and resolving constraint issue.

  • Align – Create alignment constraints, such as aligning the left edges of two views.
  • Pin – Create spacing constraints, such as defining the width of a UI control.
  • Issues – Resolve layout issues.
  • Resizing – Specify how resizing affects constraints.
Xcode Auto Layout Menu in Interface Builder

Other than the Auto Layout menu, Apple has made it flexible for developer to setup Auto Layout by using Control+drag. You simply control-drag from any view to another view to set constraints between each other. When you release the mouse, it presents a list of possible constraints for you to select from.

Auto Layout Control Drag

Once you setup a constraint in a view, the constraint line is displayed in either in orange or blue. The orange constraint lines indicates that there are insufficent constraints and you need to fix it.

Auto Layout - Missing Constraints

The blue constraint line indicates that your view layout is being setup correctly and there is no ambiguity.

Auto Layout - Constraints Defined Correctly

Sometimes after you create the constraint, the Interface Builder outline view shows a disclosure arrow. The red arrow also indicates that there are conflicts or ambiguities. Click the disclosure arrow, and you’ll see a list of the issues. The issues are displayed on a scene-by-scene basis. Typical issues include missing constraints, conflicting constraints and misplaced views.

Screen Shot 2014-06-13 at 1.41.28 AM

In the Size Inspector, you can view a list of all the constraints that have been added. These constraints appear in a section called “Constraints”.

In addition to the size inspector view, the constraints also appear in the Interface Builder Outline under the corresponding view.

Auto Layout Example – Center a Button or Image

By now, you should have a basic understanding of Auto Layout and how you can configure constraints. Let’s consider the example again and see how we can center a button or an image.

As mentioned before, Auto Layout is a constraint-based layout system. It allows developers to create an adaptive interface that responds appropriately to changes in screen size and device orientation. Okay, it sounds good. But what does the term “constraint-based layout” mean? Let me put it in a more descriptive way. Consider the “Press Me” button again, how do you describe its position? Probably you’ll describe like this.

The button should be centered both horizontally and vertically, regardless of the screen size.

Here you already define two constraints (centered horizontally and centered vertically). These constraints express rules for the layout of label in the interface. Auto Layout is all about constraints. The constraints, however, are expressed in mathematical form. For example, if you’re defining the position of a button, you might want to say “the left edge should be 30 points from the left edge of its containing view.” This translates to button.left = (container.left + 30).

Okay, that’s quite enough for the Auto Layout concept.

Now let’s see how to center an image view in the middle of the screen regardless of the screen size and orientation (portrait / landscape).

Screen Shot 2014-06-14 at 12.31.17 PM

Assuming you’ve added an image view and placed it in the center of the view, the first step is to add the width and height constraints. In this example, we’ll show you how to use Auto Layout menu to apply the constraints. Select the image view and then click the Pin icon in the Auto Layout menu. Select height and width, then hit the “Add 2 constraints” button.

Auto Layout - Adding Size Constraints

You may notice that a red arrow appears in the Interface Builder outline. This tells us that there are some constraint problems with our image view. Xcode can help us fix them. Simply click on that red arrow, followed the red indicator and finally click “Add missing constraints”.

missing constraints

Okay, we have set the size constraints. Next we’ll set another constraint to centre the image view even if the users rotate the device to landscape orientation. To do that, select the image view and click the Alignment icon in the Auto Layout menu. In the pop-over menu, select both “Vertical center in container” and “Horizontal center in container” options, followed by clicking the “Add Constraints” button.

Screen Shot 2014-06-13 at 1.04.19 PM

Now you’re ready to test your app. Compile and launch the App. Try to switch between portrait and landscape mode. You will see that the image view stays centered.

Auto Layout By Example - Centre Image

Here we just demonstrate how to use Auto Layout menu to add constraints. You can do the same thing by using control-drag. The below image illustrates how it can be done.

Auto Layout - Center Button

Auto Layout Example – Login Button

As you know, the display of iPhone 5 and iPhone 4 are of different size. It will need some tweaks to support both screen size. Consider the below login screen, the login button is placed at the bottom of the view. If you haven’t applied Auto Layout, the app may not be able to display the login button on a 3.5-inch device.

Auto Layout - Login Button

So how can you resolve this issue? Again, to fix that we need to setup a constraint to make it stay to the bottom of the screen. On top of that, its width should be changed when it’s in the landscape mode.

First we’ll add a size constraint for the height of the button. We only add a constraint for the height as the width will change depending on the device’s orientation. control-drag vertically the button and choosing “height”, then fix the ambiguity in the Interface Builder Outline by adding all the missing constraints.

Auto Layout - Set Height Constraint

To ensure the button maintains the same distance from the sides of the view (whether it’s in portrait or landscape mode), we need to add another constraint. Control-drag from the button to the left side of the superview and select “leading space to the container”. Repeat the same procedure for the right side and select “trailing space to the container”.

Auto Layout - Trailing and Leading

The last step is to add a constraint such that the button stays to the bottom of the view. Control-drag from the button to the bottom of the superview and select “bottom space to bottom layout”.

Auto Layout - Bottom space to bottom layout

Now, you can build and run the project on any devices. Thanks to Auto Layout. The login button should display correctly on 3.5-inch iPhone. And the login button scales proportionally when the device is rotated.

Auto Layout - Landscape

What’s Coming Next

In this tutorial, we covered the basics of Auto Layout using Interface Builder. I hope you start to love Auto Layout after going through the tutorial and examples. Auto Layout is very powerful once you manage the basics. You’ll be able to build adaptive UI to fit multiple screen sizes. In the upcoming tutorials, we will cover more Auto Layout examples and show you how to use Auto Layout programmatically.

For your complete reference, you can download the Xcode project from here.

What do you think about the tutorial and Auto Layout? Leave me comment and share your thought.

iOS
A Beginner’s Guide to In-App Purchase Programming in iOS 8
iOS
iOS Programming Basic: How Does the Hello World App Work?
iOS
Introduction to iOS 8 App Extension: Creating a Today Widget
  • Glory

    GloryGlory

    Author Reply

    Thanks!!!! You have done a very good job. How about the autolayout by coding?


    • Siginur Alexey

      It’s interesting for me too…
      I Have Problems with UITableView…


  • Adam Dehaven

    Keep the auto layout tutorials coming!


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Thanks Adam! Great to see that you like auto layout.


  • AAN

    AANAAN

    Author Reply

    Thanks a lot !.. Waiting for more !


  • Jack Daniel

    but what about finished and already existing apps? how we can change them to the new layout?


  • Sadik Hasan

    Thanks for the tutorial, I have been waiting for this. If you keep this run on auto layout, I think you are going to help majority of iOS app developers to fix their design issues. Thank you so much.


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Thanks for your words. Glad to hear the tutorial is helpful. We’re working on the next Auto Layout tutorial. Stay tuned.


  • Salman Khan

    kindly show steps briefly


  • jack kishore

    Thanks for the tutorial…. I need more tutorial still.


  • KingMax

    KingMaxKingMax

    Author Reply

    thank you. I have trouble with auto layout in my iOS app, until i read the tutorial.


  • Ardi Al Haidar

    Thanks. I start to love Auto Layout 😀


  • napolux

    napoluxnapolux

    Author Reply

    (in the part about the login button…) “then fix the ambiguity in the Interface Builder Outline by adding all the missing constraints.” How can I fix it? It’s not really clear from the tutorial


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      In the Document Outline of the Interface Builder, you should see a red arrow indicator. Click it and then click the red indicator, followed by selecting “Add missing constraints”.


  • Satheesh

    SatheeshSatheesh

    Author Reply

    As you said, I have started loving auto layout


  • Kashif Jilani

    Its Amazing, waiting for second tutorial.


  • answerhuang

    How to use auto layout when I need change size of a view or a control between different screen size.


  • xiaoyan

    xiaoyanxiaoyan

    Author Reply

    Yes,I like auto layout very much.
    But how can I use it with pure code and How can I use it without storyBoard?
    Thank you


  • fds fdsa

    fds fdsafds fdsa

    Author Reply

    What do I think about autolayout? It’s crap. I followed your instructions on the button exactly and the damn button does not appear. I have xcode 6 running in mavericks. Is there a bug


    • Денис

      ДенисДенис

      Author Reply

      Don’t be so angry. It works. And everything is okay. I think it’ll be better if you try to explain after what step you see the problem.


    • Jasper

      JasperJasper

      Author Reply

      I experienced the same problem, and it was because I didn’t resize the button horizontally first. The idea is to have the constraint of 0 distance from your button’s left edge to the container’s left edge, and 0 distance from the button’s right edge to the container’s right edge. What I did at first was, since I didn’t resize the button, and it was 200 pixels away from the left edge, I unwittingly asked Autolayout to enforce that distance between the button and the container edge – and this pushed the button outside the screen.


    • Alex

      AlexAlex

      Author Reply

      Autolayout is the worst instruments I used from years….just crap!!!


  • Ahmad Azar

    Ahmad AzarAhmad Azar

    Author Reply

    Nice job thank you for help me about autolayout 😀 I like it


  • Özgür Özkan Akdemirci

    For two days i was trying to follow and understand the tutorials about auto layout. At last i was able to complete your button example. Now it’s my app’s turn. Hope i’ll complete easily =). Thanks…


  • Wendell Beverly

    I’m still plagued by autolayout woes. I have 7 image and button views on my main view, and I’ve tried and tried to use autolayout, both using the “Add missing constraints” and doing it all manually myself, and it never works out well. Views get misplaced, are sized wrong, and sometimes disappear off the visible area altogether.
    Still not in love with autolayout, but I’ll keep plugging away at it as I see the potential benefit, just haven’t figured it all out yet.


    • Денис

      ДенисДенис

      Author Reply

      Could you show me your project? maybe by means dropbox, I think I can help you. There are some features when you’re debugging constraints. You have to do correct choose on that step.


  • Sagar Sandy

    Thanks man, nice introduction..


  • Chris Norwood

    Last night I was totally frustrated with the AutoLayout feature… read you article and nailed it with ease. Very, very useful, thanks. 🙂


  • Klaus

    KlausKlaus

    Author Reply

    Hey! Nice article. But what you do with auto layout here, can easily be done without auto layout. I thought I’d find some infos here about the sense and situations, where you set constraints between elements on the same ‘level’. And also, how you set up device dependent constraints. But you said it’s for the very beginners, may be you could give some tip like that on another tutorial?


  • Ben Wise

    Ben WiseBen Wise

    Author Reply

    Thanks this was really helpful.


  • Bill

    BillBill

    Author Reply

    nice, lear a lot, thank you


  • Radha Krishna

    First of all big thanks for your tutorials. I am big fan of yours.

    Followed your instructions exactly. but didn’t worked for me. I tried using Xcode 6.01 and 6.1 versions, but no luck. I tried to run on 4s Simulator button just disappears.

    Could you please do one thing. Please create new project using Xcode 6.0.1 or 6.1 and decrease the button size do your instructions and run on simulator. except iPhone 6 plus simulator, all the iPhone simulators gone wrong.

    Please check once and I am waiting for your reply. if any updates are there,Please update your tutorial.
    Thanks


  • srini

    srinisrini

    Author Reply

    very nice


  • febShab

    febShabfebShab

    Author Reply

    I followed your instructions. Image is working fine but the log in button width is not coming correctly.


  • Mel

    MelMel

    Author Reply

    Thanks for a very nice tutorial!
    Waiting for more on auto layout.


  • hahaahah

    hahaahahhahaahah

    Author Reply

    why i can feel very easy….


  • jasper

    jasperjasper

    Author Reply

    Some animations are too fast. And maybe something needs to be said about the numbers (distances) – I had to figure that one out on my own. Other than that, very helpful tutorial. Thanks!


  • jasper

    jasperjasper

    Author Reply

    How did you create the screenshots and animations? what software did you use?


  • yogendra bagoriya

    Really good stuff for beginner. I am waiting for tutorial of “Programmatically Auto layout”.


  • vince

    vincevince

    Author Reply

    I been struggling with Auto Layout, until i see this article. very well-written and explained. thank you!


  • Scott

    ScottScott

    Author Reply

    Thank you very much for taking the time to write up this article – very helpful, and much appreciated!


  • NZT Solutions

    The ultimate guide of Auto-layout. It is very useful and interesting for me as i have implemented it into one of my ios Application, and it is working. I’ll provide the app link once it’ll be completed.


  • shashank dahikar

    Thanks for the tutorial. M luvin it.. where’s the next part ?


  • Sagar

    SagarSagar

    Author Reply

    nice explanation.. thanks


  • vicmmarie

    vicmmarievicmmarie

    Author Reply

    I am so stuck with auto layout. I have tried a million different ways and layouts while trying to format my project and every time everything that isn’t centered is way off to the left of the screen.


  • Bjarte Aune Olsen

    Thanks for the tutorial, made me able to finally figure out how to set the constraints properly.


  • Moataz Elmasry

    Many Thnx. I learnt a couple of stuff.!!


  • Afsal Ismail

    Thank you.


  • Sudhir Singh

    where is next tutorial of use Auto Layout programmatically.


Leave a Reply to Simon Ng
Cancel Reply

Shares