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.
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.
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;
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.