How to size images for storyboard using auto layout?

hellion picture hellion · Mar 17, 2015 · Viewed 8.9k times · Source

I'm using Sketch to create images that will be used in my Xcode 6 auto-layout storyboards. However I can not get the image sizes correct. They always appear too large and overflow the storyboard view controller. Is there a way in Xcode to see the dimensions the storyboard expects? Is there a systematic way to do this...rather than trial and error?

Answer

Denis Mysenko picture Denis Mysenko · Mar 18, 2015

Storyboard, especially in auto layout mode, doesn't expect any dimensions – dimensions will depend on device screen (in reality) or on simulated metrics (in Interface Builder in Xcode).

What matters is aspect ratio and presence of three resource files (three sizes – regular, 2x and 3x).

You can see the list of dimensions here: http://www.paintcodeapp.com/news/iphone-6-screens-demystified

So, let's say you want to insert an image that occupies the whole width of the screen, and the height is chosen automatically so that to keep the aspect ratio. What you could do:

  1. Create images in Sketch with widths of 320, 750 and 1242 pixels. Save them as image.png, [email protected], [email protected].
  2. Insert image in Interface Builder (Storyboard), add width constraint – equal as superview, instead of height constraint – keep aspect ratio.
  3. If the image looked too big, Interface Builder will complain that preview image doesn't match constraints, you will see a little yellow arrow. Click on it, choose the warning and click again – Xcode will offer you to "Update frame". That will resize the image correctly if necessary. Don't forget to choose correct scaling mode (Aspect fit?) for your image.

Moreover, you can see current width and height of the simulated screen in Metrics tab. But those will change every time you change your preview (simulated) device type.