derdida derdida - 1 year ago 133
iOS Question

Self sizing Cells,. Autolayout and hidden UIViews

i am using Autolayout to set automatically the height of a cell. But i want to use some hidden UIViews in my Cells. So in some rows they should be hidden. The problem here is, if the label is still hidden it gets recognized by autolayout and it uses the space.

So i guess i need to update the height of my label, or the height of my Constraints.

What is the correct way if i am using Autolayout to hide UIElements in a Cell?

How can i update an existing (from Storyboard) Constraint?

Edit: Found out that i am able to update Constraints with Storyboard, is that the correct way to handle that? - but which is the correct one to setup the height? (This is just a Demo Project)

enter image description here

Answer Source

This is standard task with autolayout. Currently, there are two ways of solving this task:

  1. Removing hidden views
  2. Changing constraints priority

Removing of hidden views

Looks pretty easy and you won't have any problems if you don't use UITableView (you have to put it back in prepareForReuse), UICollectionView or your data can appear while you're on screen, where you've just removed views.

Removing of views is "heavy" operation, so you need to think twice, if you pick this way.

In CustomCell.m:

- (void) prepareForReuse {
 [super prepareForReuse];
 // add removed views again
 // establish constraints

- (void) configureCell {
 // check if you need to hide a view
 [view removeFromSuperview];

Changing constraints priority

Assume, you have following cell:

View A

View B

If B sometimes can be hidden, then specify for View A following constraints: Space to B with 750 Bottom Space to superview with 500

If you set B as hidden, change space to B = 500, bottom space to superview = 750.

Undo that change in prepareForReuse

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download