Search code examples
iosswiftautolayout

Autolayout for dynamically added UIViews


I need some recommendation on how to add constraints to dynamically added UILabels

Say I have a UIView called (A) of size (screenwidth, 200) added to a UIViewcontroller view. On view A, I have set the autoresize masks on it's leading edge and trailing edge with the superview.

Now at runtime, I am adding UILabels with characters from a String. For example, if the string is "HELLO", I am adding five UILabels at equally spaced intervals for each character in HELLO.

When the orientation changes from portrait to landscape the UILabels are not evenly spaced. I haven't set any constraints on the UILabels and need some suggestion on how to add the constraints.

Is there any other solution other than constraints available to make the UILabels evenly spread out in landscape and portrait mode?

Thanks


Solution

  • In iOS 9, UIStackViews got introduced. This is a great opportunity to use them!

    The stack view will have constraints on leading, trailing and other necessary properties so that it stays where you want. The distribution of the stack view should be "Fill Equally".

    enter image description here

    Add an outlet to your VC and when needed, add your labels into the stack view!