让我们看看我有一个这样的字符串:

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

如何使UILabel像这样显示消息

五星级 BBBBB CCCCC

我不认为\n能被UILabel识别,我能在NSString中放入什么东西让UILabel知道它必须在那里创建换行符吗?


当前回答

对于任何其他人,可能有问题sizeWithFont:constrainedToSize:lineBreakMode:或任何人切换到ios8(该方法已弃用ios7),我通过使用sizeToFit来调整我的高度。

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

其他回答

如果从XML文件读取字符串,则该字符串中的换行符\n在UILabel文本中不起作用。\n不会被解析为换行符。

这里有一个小技巧来解决这个问题:

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

myLabel.text = myLabelText;

你必须替换字符串中未解析的n部分用一个硬编码NSString中的解析的n。

以下是我的其他标签设置:

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

最重要的是将numberolines设置为0 (= label中的行数无限制)。

不知道为什么苹果选择不解析从XML读取的字符串中的\n ?

对于任何其他人,可能有问题sizeWithFont:constrainedToSize:lineBreakMode:或任何人切换到ios8(该方法已弃用ios7),我通过使用sizeToFit来调整我的高度。

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

在xCode 11, Swift 5的\n工作良好,尝试以下代码:

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

在Xcode 6中,当使用换行时,你甚至可以在字符串中使用\n。它会起作用的。例如:

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;

对于那些想要一个简单的解决方案的人,请在Interface Builder中的文本标签输入框中执行以下操作:

确保你的行数设置为0。

Alt + Enter

(Alt是你的选项键)

干杯!