如何为 UILabel 添加换行符?

发布于 2024-08-22 07:21:56 字数 281 浏览 21 评论 0原文

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

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

如何使 UILabel 显示这样的消息

AAAAA
BBBB
中交会

我认为 UILabel 无法识别 \n ,所以我可以在 NSString 中放入任何内容,以便 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

雨后彩虹 2024-08-29 07:21:56

使用在字符串中使用的 \n

将 numberOfLines 设置为 0 以允许任意数量的行。

label.numberOfLines = 0;

使用 sizeWithFont: 更新标签框架以匹配文本大小。如果您不这样做,您的文本将垂直居中或被截断。

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

更新:替换已弃用的

sizeWithFont:constrainedToSize:lineBreakMode:

参考,替换已弃用的 sizeWithFont:在 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);

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);
疯狂的代价 2024-08-29 07:21:56

输入图像描述这里

在 Interface Builder 中的小框中键入内容时使用 option-return 来插入换行符 (\n)。在 Interface Builder 的 Label 属性中,设置 # Lines = 0。

选择标签,然后将 Lines 属性更改为 0,如上图所示,然后在字符串中使用 \n 进行换行。

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.

冰葑 2024-08-29 07:21:56

在界面构建器中,您可以使用 Ctrl + Enter/n 插入到您想要的位置。
这样可以实现以下情况

aaa
aaaaaaa

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

你是我的挚爱i 2024-08-29 07:21:56

如果您从 XML 文件中读取字符串,则该字符串中的换行符 \nUILabel 文本中将不起作用。 \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;

最重要的是将 numberOfLines 设置为 0 (= 标签中的行数不受限制)。

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

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?

只有影子陪我不离不弃 2024-08-29 07:21:56

您必须在 UILabel 上设置 numberOfLines 属性。默认值为1,如果将其设置为0,它将删除所有限制。

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.

命比纸薄 2024-08-29 07:21:56

重要的是要注意它是 \n (反斜杠)而不是 /n

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

烟沫凡尘 2024-08-29 07:21:56

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

确保行数设置为 0。

Alt + Enter

(Alt 是您的选项键)

干杯!

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!

作死小能手 2024-08-29 07:21:56

在 Swift 2.2 中,> iOS 8

我已在 Storyboard 上的属性检查器下设置 Lines = 0 并将引用出口链接到标签。然后在控制器中使用如下:

 @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"
 }

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"
 }
情深已缘浅 2024-08-29 07:21:56

在 xCode 11、Swift 5 中 \n 工作正常,请尝试以下代码:

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

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"
掩于岁月 2024-08-29 07:21:56

就这样做

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;

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;
橘味果▽酱 2024-08-29 07:21:56

// 不要忘记将 numberOfLines 设置为零

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

// 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];
深巷少女 2024-08-29 07:21:56

如果您使用 UILabel,您必须记住默认设置是 1 行,因此添加多少个中断并不重要(\n\r),您需要确保将其设置为多行,以便可以添加更多行。

一种替代方法是使用 UITextView,它实际上适用于多行。

您可以在 UILabel 的 XCode 属性部分轻松实现此目的,请参阅屏幕截图:

在此处输入图像描述

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

初见你 2024-08-29 07:21:56

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

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;
梦中的蝴蝶 2024-08-29 07:21:56

就我而言, \n 也不起作用,我通过将行数保持为 0 并复制并粘贴文本与新行本身来解决问题,而不是 Hello \n World i Pasted

你好

世界

界面生成器中的

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.

断念 2024-08-29 07:21:56

只需使用label.numberOfLines = 0;

Just using label.numberOfLines = 0;

何以心动 2024-08-29 07:21:56
textLabel.text = @"\nAAAAA\nBBBBB\nCCCCC";
textLabel.numberOfLines = 3; \\As you want - AAAAA\nBBBBB\nCCCCC
textLabel.lineBreakMode = UILineBreakModeWordWrap;
NSLog(@"The textLabel text is - %@",textLabel.text);
textLabel.text = @"\nAAAAA\nBBBBB\nCCCCC";
textLabel.numberOfLines = 3; \\As you want - AAAAA\nBBBBB\nCCCCC
textLabel.lineBreakMode = UILineBreakModeWordWrap;
NSLog(@"The textLabel text is - %@",textLabel.text);
天涯沦落人 2024-08-29 07:21:56

对于可能遇到 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);

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);
溺渁∝ 2024-08-29 07:21:56
NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];
NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];
转瞬即逝 2024-08-29 07:21:56

在我看来,更改标签框架大小似乎是错误的,尤其是在使用自动布局时。使用appendFormat方法似乎更合适。这是我的例子:

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;

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;
何其悲哀 2024-08-29 07:21:56

如果您将 UILable 属性从 Plain 设置为 Attributed...UILabel 将保留多行文本,无论有多少段落,因为您的 UILabel 高度和宽度设置为适合您要在其中显示文本的屏幕区域。

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.

墟烟 2024-08-29 07:21:56

我遇到了同样的问题,这是我如何解决该问题的。希望这对某人有帮助。

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

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;  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文