Autolayout - Adjust Label Y position on the basis of other label's dynamic height above it

108 Views Asked by At

I have two labels. Label A and Label B as shown below.

View with both labels

View when Label A height is 0

I want to move Label B up with top margin to superview = 20pt, when Label A height is zero.

If label A height is > 0 Then Label B Y position is = Label A top Margin + Label A height + Vertical Spacing between Label A and B. (i.e. Bottom Of Label A + Vertical Spacing b/w Label A and B = Label B Y postion) Is it possible to do it using autolayout?

1

There are 1 best solutions below

0
On

You can have all constraints for the LabelA.height > 0 case linked to a NSLayoutConstraint IBOutletCollection.

@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) *labelAScenarioConstraints;

Same for the LabelA.height = 0 scenario like

@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) *labelAWithoutHeightScenarioConstraints

And when you want to change it just do something like:

for (NSLayoutConstraint *constraint in labelAScenarioConstraints) {
    [constraint setActive:labelA.frame.size.height > 0];
}
for (NSLayoutConstraint *constraint in labelAWithoutHeightScenarioConstraints) {
    [constraint setActive:labelA.frame.size.height == 0];
}

You can activate or deactivate a constraint by changing this property...Activating or deactivating the constraint calls addConstraint: and removeConstraint: on the view that is the closest common ancestor of the items managed by this constraint. Use this property instead of calling addConstraint: or removeConstraint: directly.

Keep in mind that all the UI updates should be done from the main thread. If you want to animate the constraints change you can put the code inside UIView animateWithDuration animations block.