iosobjective-clabelsizetofit

Possible to dynamically build layout?


I have a view for a contact. Based on the contact info the user provides, I would like to either include labels if the information is available, or not take up space if the information is not available to avoid a bunch of fields like tel: email: etc. that are blank,

The page is laid out in storyboard. Is there a way to keep label from taking up space if empty or otherwise dynamically construct page?

I was thinking of [label sizeToFit]; but this still seems to leave at least one line of empty space for the label.

Edit: Shows vertical constraint set to 10.f and 0.f. The image is shrinking but not the space it occupied.

enter image description here

enter image description here


Solution

  • You can use constraints for this.

    Building programmatically an advanced layout is very complicated and error prone but using Auto-Layout options you can do this.

    For example you have a UILabel and sometimes you want to remove it from layout. So you can make a reference to your height and width constraint of that UILabel and so change as below:

    widthConstraint.constant  = 0.0f;
    heightConstraint.constant = 0.0f;
    

    Also you can keep the initial value in a property and use them when you want to add to Layout.

    ---Edited---

    For taking effect you should call [self needsUpdateConstraints]; after change of constraint.