iOS 9 will bring UIStackView and with it will make creating adaptive layout easier than ever.

This is important because with the new multitasking on iPad you want to make sure that your app can handle all possible different screen sizes.

In the past many developer had difficulties to get their head around Auto Layout. Many third party libraries tried to make the creation of layout constraints in code easier. Several books have been written about Auto Layout.

Apple addressed this with the introduction of a new API to create layout constrains in code and UIStackView. Using UIStackView you just set a few properties and add views you want to be arranged by the stack view. Under the hood UIStackView adds Auto Layout constraints to the arranged views according to the property values you have set.

It arranges its subview vertically or horizontally. You can nest UIStackViews to achieve many different layouts. In addition you can add additional constraints to the views. Changes to the properties of the stack view and its subviews are animated by default.

Sounds great, doesn't it? I love Auto Layout and therefore was exited to try what UIStackView brings to the table. As I'm not a fan of Storyboards I created a Playground to experiment with UIStackViews in code.

Examples

Here are the different layouts I've created. More to come (suggestions welcome!):

iOS Calculator

Screen Shot 2015-06-26 at 16.36.17

A Profile View

Screen Shot 2015-06-26 at 11.16.32

A Tweet/Post

Screen Shot 2015-06-26 at 11.34.54

iOS Mail Inbox

Screen Shot 2015-06-27 at 17.58.13

Some Tipps

  1. Don't forget to disable translatesAutoresizingMaskIntoConstraints when you position you stack view using Auto Layout.
  2. Views arranged by a stack view have automatically translatesAutoresizingMaskIntoConstraints disabled.
  3. If your subviews are bigger than they should be, try to set the alignment to something else than .Fill (which is the default).
  4. Spacing can be negative (see the Profile example) but I did not manage to make a spacing that is smaller that the negative of the width of the smaller subview. (I need to experiment with the distribution parameter a bit for this case.)
  5. If you add constraints to an arranged view, try to think what constraints the stack view implicitly added and don't fight those.
  6. Sometimes you need to put a stack view into a view which itself is part of a stack view.
  7. Stack views can have subviews that are not arranged (i.e. don't get implicit constrains).
  8. If you want to use stack views or the new Auto Layout API in a Playground put the code in a if #available(iOS 9, *) { } condition. Otherwise the Playground won't execute.

If you want to experiment yourself, the Playground is on github.