-2

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?

  • Where is the question.. No one knows which label you want to adjust -_- Assuming A is dynamic and you want B to move down.. Make Label A have a `contentHuggingPriority` of `.required` and `contentCompressionResistancePriority` of `.required`.. Then the top label will size itself to fit and the other one will move accordingly. – Brandon Nov 15 '18 at 14:50
  • I want to move Label B up when Label A height is zero. If Label A height is zero I want to remove vertical spacing – user10316062 Nov 15 '18 at 14:56
  • User a UIStackView.. – Brandon Nov 15 '18 at 14:57
  • Use a `UIStackView` with axis set to vertical. Use spacing of 20, alignment fill, distribution fill. Now you have to adjust the hugging priority -> set lower value for whichever label needs to grow more than the other. – nayem Nov 15 '18 at 15:37
  • Whenever you need to set the height of the label A to `0`, you would only need to set the `hidden` property of that label to `true`. – nayem Nov 15 '18 at 15:38

1 Answers1

0

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.

FedeH
  • 1,343
  • 18
  • 24