Reputation: 11755
This question may seem too simple to an AutoLayOut expert, but is still out of my own usual AutoLayOut usage.
I am used to play with the .Top
, .Bottom
, .Left
, .Right
, .CenterX
, .CenterY
attributes. But how do I do when dealing with a few objects?
For example, if I have five UILabel(s), and I want them to be vertically aligned, with a regular spacing. For the X-axis part, it is easy:
myXConstraint = NSLayoutConstraint(item: label1,
attribute: .CenterX,
relatedBy: .Equal,
toItem: superView,
attribute: .CenterX,
multiplier: 1.0,
constant: 0.0);
with a constraint like this one on each of the 5 labels, they will be vertically aligned.
But how should I write my other constraints, so that label1 appears at the top, then label2, label3 ….. label5. And I want the space at the top, the one at the bottom and the spaces between each consecutive label to be all the same value.
Upvotes: 3
Views: 85
Reputation: 2312
If you are adding it programatically and if you are deciding the number of labels at runtime, then the very first label should be associated with the superview using vertical spacing. All the rest you should set vertical spacing associated to your label which is created above it with same constant.
And if you are developing for iOS 9 onwards, then you can implement Stack View and get this functionality done with no time without implementing Autolayout.
Assuming all the labels will be added into a parent container view which is empty initially.
After creating each label, before adding to as a subview to parent container, get all the subviews. If the array count is zero, then add the constraint with respective to parent container for vertical spacing. There add it as subview
Later in the loop whenever adding any more labels, add constraint to the label respective to the previous view/label. The previous view/labels 's reference you may take it from the subView list which we will be taking it for every cycle.
The last stack will have the recently added view/labels's reference. Hence in the subview list array, the last index of the array is the label which is created just above the current view/label.
Upvotes: 1