How to add line break for UILabel?

Thang Pham picture Thang Pham · Feb 22, 2010 · Viewed 268.8k times · Source

Let see that I have a string look like this:

NSString *longStr = @"AAAAA\nBBBBB\nCCCCC";  

How do I make it so that the UILabel display the message like this

AAAAA
BBBBB
CCCCC

I don't think \n is recognized by UILabel, so is there anything that I can put inside NSString so that UILabel knows that it has to create a line break there?

Answer

Gerry Shaw picture Gerry Shaw · Feb 23, 2010

Use \n as you are using in your string.

Set numberOfLines to 0 to allow for any number of lines.

label.numberOfLines = 0;

Update the label frame to match the size of the text using sizeWithFont:. If you don't do this your text will be vertically centered or cut off.

UILabel *label; // set frame to largest size you want
...
CGSize labelSize = [label.text sizeWithFont:label.font
                          constrainedToSize:label.frame.size
                              lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(
    label.frame.origin.x, label.frame.origin.y, 
    label.frame.size.width, labelSize.height);

Update : Replacement for deprecated

sizeWithFont:constrainedToSize:lineBreakMode:

Reference, Replacement for deprecated sizeWithFont: in iOS 7?

CGSize labelSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];

label.frame = CGRectMake(
    label.frame.origin.x, label.frame.origin.y, 
    label.frame.size.width, labelSize.height);