How to set UILabel height based on the text we have

I have a UILabel 260 wide, where I have long text (maybe about 1000 characters).

I wanted to set the height of the UILabel based on the content. Sometimes I can have 100 characters, sometimes I can have 1000 characters).

Based on the text, how can I set the height of the UILabel?

Note. I am creating UILabel programmatically.

 UILabel myLabel = [[UILabel alloc] initWithFrame: CGRectMake (30,50,260, height)];

Any idea how to do this?

One of the ways I'm trying to do is as shown below.

I consider that in one line there are 40 characters. So what I do is find the length of the text and divide it by 40. This will give me the total number of lines that I need.

But this fails when new lines appear.

Is it correct?

+4
2

:

myLabel.numberOfLines = 0;
[myLabel sizeToFit];
+10
NSString * mytext = @"My string";
myLabel.font = [UIFont fontWithName:@"fontName" size:15];
CGSize sz = [mytext sizeWithFont:myLabel.font];
float height = sz.height;
float totalHeight = height*myLabel.numberOfLines;

, sizeWithFont iOS 7.

+1

All Articles