Dynamically set view top margin and height using autolayout - swift3

245 views Asked by At

I am working on a UI where I have 3 labels. All are arranged vertically-

Label 1

Label 2

Label 3

  1. List item At a time any two Label will be shown to user.
  2. For example if Label 1 and Label 3 are shown then I want to shift Label3 up below the label1 and make Label2 height to 0.
    1. If Label2 and Label3 are shown we have to shift both label up and set label1 height to 0. So everytime topmst label should have same top margin from superview. It can be either Label1, Label2 or Label3

Should I use stack view to achieve this requirement?

What is the best way to do it using auto layout?

1

There are 1 answers

0
FedeH On

You can group your different scenarios constraints in a IBOutletCollection(NSLayoutConstraint) property (one per scenario/ group of constraints) like:

@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *scenarioNConstraints;

And then based on your conditions you can Activate or Deactivate the desire constraints by doing something like

for (NSLayoutConstraint *constraint in scenarioNConstraints) {
    [constraint setActive:YES]; //or [constraint setActive:NO];
}