Search code examples
objective-cuilabelcgrectmake

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?


Solution

  • Try to use:

    myLabel.numberOfLines = 0;
    [myLabel sizeToFit];