6

I have a lot of labels stacked up for a contact info screen. If any of the labels are empty, I would love to zero out their height and have them occupy no space to avoid empty space on the screen. However, I have created the screen in storyboard and the labels have been assigned heights and y values.

Here is code I've been trying to use to alter label height but cannot get it to work. Perhaps it is designed to work only for labels created programmatically and the storyboard settings override what I am doing here.

NSString *string = @"some text"; 
CGSize maximumLabelSize = CGSizeMake(280,1000);
 
// use font information from the UILabel to calculate the size
CGSize expectedLabelSize = [string sizeWithFont:myLabel.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
 
// create a frame that is filled with the UILabel frame data
CGRect newFrame = myLabel.frame;

// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height;

// put calculated frame into UILabel frame
myLabel.frame = newFrame;

Is there a way to get the height of labels created in storyboard to zero out if they are empty?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user1904273
  • 4,562
  • 11
  • 45
  • 96
  • can you use a stack view? how does the text change? why do you have a static number of labels if you may not have that much text? – Wain Jan 04 '16 at 13:23
  • The labels are name, title, first line of address, 2nd line of address, city state, zip tel#, email... vertically stacked as on a business card. However, if title oraddress line 2 or phone number is not filled out by users, I don't want empty space there. I also am trying to avoid having Title:with a blank space. just want to display the title or email address if present, otherwise nothing. Supporting ios8 so I think that nixes stack view. – user1904273 Jan 05 '16 at 11:27
  • you could do that with a single label – Wain Jan 05 '16 at 11:35
  • First of all use autolayout. The answers in the following link could be of some help. https://stackoverflow.com/a/25898949/1612489 – Sumeet Jan 04 '16 at 13:25

1 Answers1

0

you can override the following method of the view containing your label and do something like that:

-(void) layoutSubviews {
    myLabel.frame = CGRectZero;
}

This method is in order to allow to layout the subviews or you view. Now I don't know If you have used contraints to define the height of your label. If so you should change in the same way the height of your label. Note the in the above example I used CGRectZero.

chiarotto.alessandro
  • 1,491
  • 1
  • 13
  • 31