Ios – In auto layout, How to “hide” a UIView

autolayoutiosswiftuiview

In my UITableViewCell, I have two UIViews stacked on top of each other. Let's call them Top and Bottom.

The Top view has leading, trailing, and top constraints to superview. It has a height constraint of 20.

The Bottom view has leading, trailing, and bottom constraints to superview. It has a height constraint of 20.

Top and Bottom have a vertical constraint.

What is the easiest way to programatically "hide" the Bottom View (and have the Top View touch the bottom of the superview)? I prefer not to create any more constraints, since I did design this in storyboard, and I prefer not to activate/disable constraints.

Best Answer

If you don’t need to target iOS 8 and below, the easiest way is to embed the two views in a UIStackView. You can then simply hide a view by setting its hidden property and the stack view will automatically update the layout:

The stack view automatically updates its layout whenever views are added, removed or inserted into the arrangedSubviews array, or whenever one of the arranged subviews’s hidden property changes.

Since your parent view is a table view cell, you may have to tell the table view to recalculate the cell heights (unless you’re using autosizing cells, then this may work automatically, I’m not sure). You can force a recalculation by sending the table view an empty beginUpdates/endUpdates pair:

tableView.beginUpdates()
tableView.endUpdates()