Question

I have UILabel of width 260 where I have long text (maybe around 1000 characters).

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

Based on 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 get this done?

One way I am trying is as below.

I am considering there are 40 chars in one line. So what I am doing is finding length of text and divide it by 40. This will give me total number of lines I required.

But this fails when there are new lines.

Is this right way?

Was it helpful?

Solution

Try to use:

myLabel.numberOfLines = 0;
[myLabel sizeToFit];

OTHER TIPS

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;

Note that sizeWithFont is deprecated in iOS 7.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top