Search code examples
iosxcodeautolayoutnslayoutconstraint

Align text fields using dynamic constraints


I've been learning how to make iOS apps, and have come across a minor annoyance. I can't find an easy way to align my text inputs.

Looking at the below screenshot, you will see that I've managed to align my text fields, which is what I want.

However, I did this manually by changing the individual Leading Space between each Label and Text Field.

Screenshot

My question is, how can I dynamically align my text fields?


Solution

  • Anand has posted nice way, but I personally use equal widths and heights in this kind of situation. So let's make a brief of it:

    1) First, put constraints onto the age label:

    • left leading c.
    • top leading c.
    • width c.
    • height c.

    2) Put constraints onto the top right textfield:

    • right trailing c.
    • top leading c.
    • height c.
    • the constraint, that will be related to spacing between label and textfield, so CTRL drag from textfield to label a select horizontal spacing c.

    enter image description here

    3) Then, make a second row of you elements - place second label and second textfield approximately of the same width and height in storyboard (with IB you can fix it later using magic function Update frames).

    enter image description here

    4) Then, set this for your weight label:

    • left leading c.
    • top leading c.
    • then select both labels and check equal widths checkbox, and equal heights checkbox.

    enter image description here

    enter image description here

    5) The same repeat width your second textfield. You don't have to make spacing constraint in the second step.

    enter image description here

    FINISH Now all four items are aligned.

    If you want to change height of labels for example, just select the height constraint of it and your other labels will follow this change as well.

    So final experience is here in this animation:

    enter image description here