Even Easier Percentage Widths And Centering in Storyboards with XCode 6

In a previous article I showed how to set the width of a subview to a percentage of it’s parent inside a XIB file. It wasn’t rocket science, but it wasn’t exactly simple either. The good news is, if you are in a Storyboard, it really is simple. A big tip o’ the cap to Tanya Landsman from Cars.com for showing me this.

Setup

Create a single view app or any other app, actually, as we will be using the Main.storyboard file that comes along with new projects in XCode 6.

Once the project opens, select the Main.storyboard file in the Navigator to start working on it. Now we do exactly what we did for the XIB version:

Add A Thing

Drag in a UIView in roughly the middle of the parent view. This will be the view we work with. While it’s selected, use the Attributes Inspector to change the color to something other than white so we can see it. I have selected a boring grey. You make a better choice!

Make it square

While it’s still selected, use the Size Inspector to enter a height and width that will make it square. The values themselves aren’t important (I used 200 if you want to copy me) as long as the view has the aspect ratio you want. You can also drag it to the center of the superview, but it’s not needed, as it’s position and size will be changed by the constraints we add later.

XCode 6 screenshot

A Boring Square UIView

You are almost done

No, really. That was the hard part. Now you are going to Ctrl-Drag from your subview a couple times:

  1. Drag to the left and pick Center Vertically in Container
  2. Drag up and pick ‘Center Horizontally in Container`
  3. Drag to itself and pick Aspect Ratio
  4. Drag up again and pick Equal Widths

How fun!

Change one value

Select that last constraint you made (the Equal Width one) and in the Attributes Inspector, change the Multiplier value from 1 to 0.5. This makes your subview half as wide as the parent. Congrats, you are finished. Here’s a video of the whole process:

Storyboard Only!

Remember, this will only work in Storyboards: XIB files won’t allow you to make that Equal Widths connection to the superview for some (probalby very good) reason.


Thanks for reading, and until next time, happy coding! I would love to hear feedback or answer any questions via twitter: @veddermatic or by email

back to top