Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set height of UILabel based on the text we have

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?

like image 407
Fahim Parkar Avatar asked Dec 19 '22 22:12

Fahim Parkar


2 Answers

Try to use:

myLabel.numberOfLines = 0;
[myLabel sizeToFit];
like image 61
Javi Campaña Avatar answered Feb 24 '23 01:02

Javi Campaña


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.

like image 21
Nirav Bhatt Avatar answered Feb 24 '23 02:02

Nirav Bhatt