How to add line break for UILabel?

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?


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);

enter image description here

Use option-return when typing in the little box in Interface Builder to insert a line feed (\n). In Interface Builder's Label attributes, set # Lines = 0.

Select the label and then change Lines property to 0 like in the above image, and then use \n in your string for line break.


In the interface builder, you can use Ctrl + Enter to insert /n to the position you want. This way could implement the following situation

aaa
aaaaaaa