Satyam Raikar
Satyam Raikar

Reputation: 473

iOS autolayout constraints refresh

Main question : I have three labels (label1, label2, label3) one below the other. How do I align label3 below label1 if, during runtime, label2 is set to hidden or if removed from superview.

Initial View:

Label1
vertical spacing 
Label2
vertical spacing 
Label3

Action:

set Label2.hidden = yes;

Output:

Label1
vertical spacing
Label3

What I have tried is to apply vertical spacing constraints:

  1. between label1 and label2 with some priority
  2. between label2 and label3 with high priority wrt to 3rd constraint
  3. between label1 and label3 with lowest priority

Now when I remove the label2 how do I refresh the constraints or should I keep track of all constraints and remove the 2nd constraint when label2 is hidden?

Upvotes: 1

Views: 1347

Answers (2)

SushiGrass Jacob
SushiGrass Jacob

Reputation: 19834

A solution would be to change the height constraint on label2 so that it's zero and then refresh the constraints so that everything moves up. You'd have to make a property of that variable and set it with +(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;

A couple tips:

  • Make sure you remove, change and re-add the constraint from the label, not the label's superview.
  • You can use all of the same values for the existing constraint for the new one with, of course, the exception of the constant which would be 0.

Good luck!

Upvotes: 1

progressiveCavemen
progressiveCavemen

Reputation: 529

Why not just change label3's frame to equal label2 when you set it to hidden?

So add Label3.frame = Label2.frame; after Label2.hidden = YES; and vice versa.

Upvotes: 0

Related Questions