Hiding a UIView using AutoLayout constraints Hiding a UIView using AutoLayout constraints ios ios

Hiding a UIView using AutoLayout constraints


You can do this by adding an extra constraint between the yellow and red views of a lower priority, and adjusting the priorities in code.

enter image description here

The short dashed constraint (orangeToRedCon is the outlet) has a priority of 999 (you can't change a required priority to a non-required, so that's why it's not 1000). The long dashed constraint (yellowToRedCon) has a priority of 500 and a constant of 20. In code, you can hide the orange view, and swap those priority levels, and that will cause the yellow view to move up to whatever value you've set for the constant value of yellowToRedCon.

-(void)changePriorities {    self.yellowToRedCon.priority = 999;    self.orangeToRedCon.priority = 500;    [UIView animateWithDuration:.5 animations:^{        self.orangeView.alpha = 0;        [self.view layoutIfNeeded];    }];}

This method doesn't require any changes in the orange view's height.


In iOS 9 you can use UIStackView for this.There also are polyfills for older versions: TZStackView and OAStackView


What you could do is have the height constraint of the orange view as an outlet (to be able to access it).then animate the collapse like so:

[UIView animateWithDuration:0.3 animations:^{    orangeHeightConstraint.constant = 0;    [self.view layoutIfNeeded]}];

The orange view will have to have a top constraint to the red view and a bottom constraint to the yellow view.Also make sure to check Clip Subviews in IB or [orangeView clipsToBounds] programatically