Regular distance with AutoLayout
This question may seem too simple to an AutoLayOut expert, but is still not used in my usual AutoLayOut use. I used to play with attributes
. But how should I do when you are dealing with multiple objects?
For example, if I have five UILabel (s) and I want them to be vertically aligned at regular intervals. For the X-axis part, it's easy:
myXConstraint = NSLayoutConstraint(item: label1, attribute: .CenterX, relatedBy: .Equal, toItem: superView, attribute: .CenterX, multiplier: 1.0, constant: 0.0);
with a constraint like this on each of the 5 labels, they will be vertically aligned.
But how do I write other constraints so that label1 appears at the top, then label2, label3 ..... label5. And I want the space at the top, one at the bottom, and the spacing between each successive label to be the same.
source to share
If you add it programmatically and if you define the number of labels at runtime, then the very first label should be associated with the superview using vertical spacing. Everything else you have to set the vertical distance associated with your label being created above it with the same constant.
And if you are developing for iOS 9 then you can implement Stack View and get that functionality without any time without implementing Autolayout.
Suppose all labels are added to the view of the parent container, which is initially empty.
After creating each label, before adding it as a child to the parent container, get all subzones. If the array count is zero, add a constraint with the appropriate parent container for vertical spacing. Add it as a subview
Later in the loop, when you add more labels, add a label constraint to match the previous view / label. The previous view / labels refers to it from the list of subviews that we will take for each loop.
The last stack will add a link to new links / labels. Hence, in the subview list array, the last index of the array is the label created just above the current view / label.
source to share