3
votes

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.

3

3 Answers

6
votes

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()
2
votes

The right way:

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

The Bottom view has leading, trailing, bottom constraints to superview and top constraint to Top view.

Than just make a property for height Constratint inside your cell:

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *heightConstraint;

Than when you need to change the size, call this code:

self.heightConstraint.constant = 40;
[self.view layoutIfNeeded];

or with animation:

self.heightConstraint.constant = 40;
[UIView animateWithDuration:0.3 animations:^{
    [self.contentView layoutIfNeeded];
}];
1
votes

You can increase the height constraint of the top view to 40 and reduce the height constraint of the bottom view to 0. Personally I prefer to have the bottom view height constraint to 20 and add a constraint to the topView bottom equal to bottomView top. And if i want to hide the bottomView I just change the height constraint of the bottomView to 0. Hope it helps. If you need I can post some pictures in Xcode.