\\n not working in UIlabel

2019-04-07 11:28发布

问题:

I've seen similar questions here, but still can figure out why it's not working.

How to add line break (in other words add new paragraph) in multiline UIlabel?

I have a label with a lot of text,

lbl.numberOfLines = 0;
lbl.sizeToFit;

but I'm still getting something like this: "Some text here\nAnd here I want new line"

Thank you

回答1:

UILabel won't respect \n, You can use option-return (in Interface builder) to force where you want a line break.

You can use a UIWebView in place of the label and then you can format however you like. (And set the lineBreakMode as AngeDeLaMort says above.)



回答2:

This is an old question, but just wanted to let you know that \r works like a charm :)



回答3:

You can try this One :

lbl.text = @"My \n label";
lbl.numberofLines = 0;


回答4:

This should work:

lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;


回答5:

actually there is a way to do that. try

    unichar chr[1] = {'\n'};
NSString *singleCR = [NSString stringWithCharacters:(const unichar *)chr length:1];
    [yourLabel setText:[NSString stringWithFormat:@"new%@line",singleCR]];


回答6:

If your string is really ok, maybe you can try adding this line as well:

lbl.lineBreakMode = UILineBreakModeWordWrap;


回答7:

Your issue may be different... but mine was a literal character \n, which is actually \\n in memory.

I solved it with:

label.text = [rawText stringByReplacingOccurrencesOfString@"\\n" withString:@"\n"];

You still need to set line break mode as well as numberOfLines for it to work.



回答8:

use ctrl + Enter in storyboard, and make number of lines as 0



回答9:

I know it's old question, but i was wondering - could the problem be lbl.sizeToFit; ?

if you could set frame like CGRectMake(0,0,300,300) - does that solves the problem? Because \n works on my side.



回答10:

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


回答11:

UILabel use \n to made new line. \n need a space in the back.



回答12:

This is old question but if any one want to do from interface builder.then it is easy and simple

select label and change type to attributed by default it is plain

now wherever you want to \n there just use Alt + Enter and you will get new line

hope it is helpful to someone who is using interface builder to achieve this