[ios] 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?

This question is related to ios iphone uilabel newline line-breaks

The answer is


In my case also \n was not working, I fixed issue by keeping number of lines to 0 and copied and pasted the text with new line itself for example instead of Hello \n World i pasted

Hello

World

in the interface builder.


textLabel.text = @"\nAAAAA\nBBBBB\nCCCCC";
textLabel.numberOfLines = 3; \\As you want - AAAAA\nBBBBB\nCCCCC
textLabel.lineBreakMode = UILineBreakModeWordWrap;
NSLog(@"The textLabel text is - %@",textLabel.text);

For those of you who want an easy solution, do the following in the text Label input box in Interface Builder:

Make sure your number of lines is set to 0.

Alt + Enter

(Alt is your option key)

Cheers!


For anyone else that might have trouble with sizeWithFont:constrainedToSize:lineBreakMode: or anyone switching to ios8 (the method is deprecated as of ios7), I adjusted my height by using sizeToFit instead.

UILabel *label;
label.numberOfLines = 0;
// Setup label with desired settings
...
[label sizeToFit];
label.frame = CGRectMake(label.frame.origin.x,     // Or use any desired origin
                         label.frame.origin.y, 
                         label.frame.size.width,   // Or use any desired width
                         label.frame.size.height);

You have to set the numberOfLines property on the UILabel. The default is 1, if you set it to 0 it will remove all limits.


I have faced same problem, and here is, how i solved the problem. Hope this will be helpful for someone.

// Swift 2

   lblMultiline.lineBreakMode = .ByWordWrapping // or use NSLineBreakMode.ByWordWrapping
   lblMultiline.numberOfLines = 0 

// Objective-C

  lblMultiline.lineBreakMode = NSLineBreakByWordWrapping;
  lblMultiline.numberOfLines = 0;

// C# (Xamarin.iOS)

  lblMultiline.LineBreakMode = UILineBreakMode.WordWrap;
  lblMultiline.Lines = 0;  

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


Important to note it's \n (backslash) rather than /n.


If you set your UILable properties from Plain to Attributed...the UILabel will hold multiline text no matter how many paragraphs for along as your UILabel height and width are set to fit the screen area you want to display the text in.


In Swift 2.2, > iOS 8

I've set Lines = 0 on Storyboard, under Attribute Inspector and linked a referencing outlet to the label. Then use in controller like this:

 @IBOutlet weak var listLabel: UILabel!

 override func viewDidLoad() {
      ...
      listLabel.text = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8"
 }

Just do it like this

NSString * strCheck = @"A\nB";

strCheck = [strCheck stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];  //This is to prevent for fetching string from plist or data structure

label.numberOfLines = 0;

label.lineBreakMode = NSLineBreakByWordWrapping;

label.text = strCheck;

If your using a UILabel you have to remember that the default setting is 1 line, so it does not matter how many breaks you add (\n or \r), you need to make sure it is set to more than one line so it could be allowed to append more lines.

One alternative is to use UITextView which is really meant for multilines.

You can easily achieve this in XCode attribute section of the UILabel, see screenshot:

enter image description here


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.


Just using label.numberOfLines = 0;


// DO not forget to set numberOfLines to zero

UILabel* locationTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 30, 230, 40)];
locationTitle.font = [UIFont systemFontOfSize:13.0];
locationTitle.numberOfLines = 0;
locationTitle.text = [NSString stringWithFormat:@"Eaton industries pvt. Ltd \nUK Apr 12"];
[cell addSubview:locationTitle];

On Xcode 6, you can just use \n even inside a string when using word wrap. It will work. So for example:

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, screenRect.size.width, 50)];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"This will be on the first line\nfollowed by a line under it.";
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;

NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];

It seems wrong to me to change the label frame sizes especially when using autolayout. Using the appendFormat method seems more appropriate. Here is my example:

NSMutableString *list = [[NSMutableString alloc] init];
NSArray *textArray = @[@"AAAA", @"BBBB"];
for (NSString *string in textArray) {
    [list appendFormat:@"%@\n", string.mutableCopy];
}
self.label.text = list;
self.label.numberOfLines = 0;

If you read a string from an XML file, the line break \n in this string will not work in UILabel text. The \n is not parsed to a line break.

Here is a little trick to solve this issue:

// correct next line \n in string from XML file
NSString *myNewLineStr = @"\n";
myLabelText = [myLabelText stringByReplacingOccurrencesOfString:@"\\n" withString:myNewLineStr];

myLabel.text = myLabelText;

So you have to replace the unparsed \n part in your string by a parsed \n in a hardcoded NSString.

Here are my other label settings:

myLabel.numberOfLines = 0;
myLabel.backgroundColor = [UIColor lightGrayColor];
myLabel.textColor = [UIColor redColor]; 
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
myLabel.textAlignment = UITextAlignmentCenter;

Most important is to set numberOfLines to 0 (= unlimited number of lines in label).

No idea why Apple has chosen to not parse \n in strings read from XML?

Hope this helps.


In xCode 11, Swift 5 the \n works fine, try the below code:

textlabel.numberOfLines = 0
textlabel.text = "This is line one \n This is line two \n This is line three"

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to uilabel

How to make a UILabel clickable? Figure out size of UILabel based on String in Swift How to underline a UILabel in swift? Adding space/padding to a UILabel How to set textColor of UILabel in Swift Adjust UILabel height to text Setting UILabel text to bold How do I make an attributed string using Swift? How do I change the font size of a UILabel in Swift? how do I change text in a label with swift?

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7

Examples related to line-breaks

HTML5 tag for horizontal line break Split string in JavaScript and detect line break Match linebreaks - \n or \r\n? How to linebreak an svg text within javascript? What is the difference between a "line feed" and a "carriage return"? Bash: Strip trailing linebreak from output How to read a file without newlines? How to break lines in PowerShell? How do I specify new lines on Python, when writing on files? How to remove line breaks (no characters!) from the string?