Pedro Costa Pedro Costa - 10 months ago 78
iOS Question

Xcode 6 auto layout programmatically?

My problem is on this image:

I have this problem with Xcode 6 and I would like to know if there is a way to solve this problem programmatically... I would like to write a code which adapt my view controller to all devices... Is it possible??
(I already tried auto layout manually but I am really bad)...


Seems like you've implemented too strict constraints. As I see on screenshot, you've probably set a strong width constraint for your buttons and inputs instead of equal widths or equal spacing between each other. Make your constrains more flexible. Prefer >=,<= constraints, equal widths constraints, leading/trailing constraints. You will need more of them in comparison to strict ones, but you'll get a true adaptive layout.

To get flexible equal spacing between views, you might find helpful a conception of spacer views. In short, place a transparent UIView and set some constraints to it. To know more, read apple docs. If you like videos more (like I do :)) - watch wwdc videos, they are great. For example, Auto Layout by Example or Taking Control of Auto Layout in Xcode 5.

As an example of equally arranged buttons take a look at this screenshot: spacer views screenshot This is done with a little bit complex, but understandable constraints set:constraints screenshot

All the buttons has the equal widths constraints for each other. All spacer views has equal width constraints on each other. Each spacer view has leading/trailing constrains to buttons or parent view leadings/trailings.

With iOS 9 you have a few more options:

  • instead of spacer views you can use UILayoutGuide
  • UIStackView allows to achieve the same layout with no constraints at all

I suggest you to watch new WWDC 2015 videos, "Mysteries of Auto Layout",Part1 and Part2