Search code examples
iosswiftxcodeautolayoutnslayoutconstraint

How to automatic set constraints to make a uniform distance between UIViews?


I've a ViewController that have some components, UILabels and UITextFields. I wants that the distance between them is uniform, 2 Points Top and Bottom, for example. So far, I adjust manually the distance. I wants know if exists a way to make this automatically. I tried select all UIViews and set constraints, but not works.

Actually layout:

enter image description here

When I tried set all components constraints:

enter image description here

Not works perfectelly:

enter image description here


Solution

  • I wants that the distance between them is uniform, 2 Points Top and Bottom, for example.

    For this kind of work UIStackView do the best job. Simply select all view, check Embed In Stack:

    enter image description here

    And then specify the Spacing value (note, that sometimes you also need to change the Axis parameter, but in most cases initial value is correct for your ui elements):

    enter image description here

    Result (distance between all labels is 8):

    enter image description here