Search code examples
iphone

How to adjust and make the width of a UILabel to fit the text size?


In my project, there is a UILabel with text. The font size is 16pt. The text contents are changed depending on different cases. I hope it can automatically adjust the width of UILabel to fit the total width of texts without stretching.

Is it possible?


Solution

  • This assumes you have already set the font:

    label.text = @"some text";
    [label sizeToFit];
    

    You will also need to define a maximum width, and tell your program what to do if sizeToFit gives you a width greater than that maximum.