Reputation: 26476
From time to time I have a subview that I would like to remove from a layout. Not only should it be hidden, but it should not be considered part of the view's 'flow', so to speak. An example:
I am looking for a strategy to hide the orange view programmatically. The layout of the boxes, and their content, is via autolayout. Two things to note:
My best suggestion is to add a constraint to the orange box, setting it's height to 0. For this to work, I need to use non-required priorities for all of the vertical constraints inside the orange box. At the same time, the container should update the constant for the constraint that separates the boxes. I don't like this approach so much since the orange box class is defining it's internal constraints with it's superview's behavior in mind. Perhaps I could live with it if the orange box view instead exposes a 'collapse' method that adds the 0 height constraint itself.
Is there a better approach?
Upvotes: 33
Views: 26282
Reputation: 11745
In iOS 9 you can use UIStackView
for this.
There also are polyfills for older versions: TZStackView and OAStackView
Upvotes: 17
Reputation: 104082
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.
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.
Upvotes: 73
Reputation: 5891
I would solve this by including all "necessary" spaces of a subview as part of the subview itself. This way, 1. Red View Height = visible red part + bottom space 2. Orange View Height = visible orange part + bottom space 3. Yellow View Height = visible yellow + bottom space
When you set the Orange View Height to 0 by Autolayout, it will automatically shrink the bottom space to 0 as well.
Upvotes: 0
Reputation: 637
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
Upvotes: 1