Jonty Morris
Jonty Morris

Reputation: 807

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?

Upvotes: 0

Views: 779

Answers (2)

pedrouan
pedrouan

Reputation: 12910

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

Upvotes: 1

Anand Nimje
Anand Nimje

Reputation: 6251

Need to fix width of every label, every textfield's X- coordinate distance should me same according to bottom textfield's make sure every label's width should be same then add constraints to textField.

enter image description here

Upvotes: 1

Related Questions