Centering elements in Interface Builder is very simple, because Xcode will snap items to the vertical or horizontal center of the canvas, the same way that other Apple apps help you center items in a document (Pages and Keynote are the first examples that came to my mind).

However, when it comes to iOS apps, just because an element looks centered in the canvas, doesn’t mean that it will be centered all the time on every device: if you switch to a device with a different screen size (even in the simulator), the elements won’t be centered anymore.

This is because, in Interface Builder, you place elements with fixed positioning by default. If you want your app to look the same on every screen size, you will have to use a technique called Auto Layout.

What is Auto Layout

Auto Layout is a feature in Xcode that allows you to specify constraints on your view objects, relative to other objects in the scene. In other words, it allows you to place elements on the canvas by looking at the other elements already present on it, so you can say something like “position this new element in the middle of its containing element”.

This way, no matter what the screen size of the device, the element will always be centered.

How to access the Auto Layout menus

Right below the canvas in Interface Builder, you should see this bar:

The highlighted section is your Auto Layout menu.

How to use Auto Layout to center elements on the canvas

Easy peasy. Simply select the view object you want to center (a button, a label, whatever) and click on the third icon (the Align icon) in the list to bring up the Add New Alignment Constraints window:

Now tick Horizontally in Container, if you want to center the element horizontally, or Vertically in Container if you want to center the element vertically instead:

Once you have made your choice, click on Add 1 Constraint to save the constraint.

Now, on any screen size, this element will always be correctly centered.


Auto Layout does not limit you to centering elements on the screen, of course. It’s a powerful tool, but for this tutorial we will stop at the Align feature. Now we are able to center elements (or, more precisely, view objects) on the screen, both horizontally and vertically, no matter what the screen size of the device our app is going to run on. Pretty sweet eh :)