1

I have a:

NSString *text = @"A string of x letters of text goes here";

I then have a UILabel that with a specific font and font sie and the label will have a width of 310.

How do I create it so the height is dynamic? I want it to fit perfectly.

cdub
  • 24,555
  • 57
  • 174
  • 303
  • see height creation part of this answer http://stackoverflow.com/questions/19215199/dynamically-size-uitableviewcell-according-to-uilabel-with-paragraph-spacing/19217965#19217965 – Shankar BS Nov 18 '14 at 06:12

2 Answers2

0

Try this,

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 35)];//set the correct width here
NSString *text = @"A string of x letters of text goes here";
label.text = text;
CGSize constrainedSize = CGSizeMake(label.frame.size.width  , 9999);

//TODO:change the font properties to yourown
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,
                                      nil];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary];

CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

if (requiredHeight.size.width > label.frame.size.width) {
    requiredHeight = CGRectMake(0,0, label.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = label.frame;
newFrame.size.height = requiredHeight.size.height;
label.frame = newFrame;
Neenu
  • 6,848
  • 2
  • 28
  • 54
0

If you are using auto layouts. Just set the numberOflines = 0 . Note : Do not pin the hight of the label.Based on the other constraints it will automatically grow its size to fit the string.

Vignesh
  • 10,205
  • 2
  • 35
  • 73