8

I'm creating a basic form with various fields. I'd like to use UIStackView to layout all the controls. How would I do the following so the controls are aligned correctly? Is the UIStackView the correct way to do this?

enter image description here

Mr Rogers
  • 6,091
  • 2
  • 32
  • 34

2 Answers2

8

Apple suggests creating horizontal stack views with each label and field, and then putting them in a vertical stack view.

This makes sense in that if you later change one of controls to a different control (say a popup button), you can keep the label and control baselines aligned.

Mark Lilback
  • 1,154
  • 9
  • 21
7

You can definitely use StackViews to achieve this.

How you arrange your StackViews depends on how you want to manage your alignment.

Here's what I recommend:

  1. Put your labels in one vertically aligned stackview and
  2. Put your text fields in another vertically aligned stackview
  3. Put the two stackviews in a horizontally aligned stackview

You'll likely want to set your distribution to fill equally on the two smaller stackviews, and then set the spacing to be the same for each smaller stackview. Finally, you'll be able to set the spacing on the horizontal stack view to set the space between your text and your textfields. (That final part the reason I would set them up like this.)

Rob Norback
  • 6,401
  • 2
  • 34
  • 38
  • I think that totally fills the requirements for my question. What if the layout is a bit more complex? Say there's a visual line separating the two rows. What then? – Mr Rogers Oct 07 '15 at 17:29
  • Then I would have two horizontal stackviews containing your text and textfields, and one vertical stackview containing all of the elements (stackview, seperator, stackview). You can still achieve the same effect, just slightly less elegant. Also if it satisfies your question do you mind accepting the answer? Cheers! – Rob Norback Oct 07 '15 at 17:36
  • Done. When split up like that how do you control the left space so that the text fields are lined up correctly? – Mr Rogers Oct 07 '15 at 17:55
  • 1
    Put the same width constraint on all your text fields. – Rob Norback Oct 07 '15 at 18:13
  • @RobNorback How to handle keyboard up event. If there is submit button I would like it to be always above the keyboard. – Sagrian Jul 24 '18 at 06:14