UILabel中的多行文本

时间:2023-01-23 19:17:29

Is there a way to have multiple lines of text in UILabel like in the UITextView or should I use the second one instead?

是否有一种方法可以像UITextView那样在UILabel中使用多行文本,或者我应该使用第二行文本?

24 个解决方案

#1


737  

I found a solution.

我找到了一个解决方案。

One just has to add the following code:

只需添加以下代码:

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0 

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

Restored old answer (for reference and devs willing to support iOS below 6.0):

恢复旧答案(供参考和开发人员支持iOS 6.0以下):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

On the side: both enum values yield to 0 anyway.

另一方面:无论如何,这两个枚举值的收益率都为0。

#2


124  

In IB, set number of lines to 0 (allows unlimited lines)

在IB中,将行数设置为0(允许无限行)

When typing within the text field using IB, use "alt-return" to insert a return and go to the next line (or you can copy in text already separated out by lines).

当使用IB在文本字段中输入时,使用“alt-return”插入一个返回并转到下一行(或者您可以在用行分隔的文本中复制)。

#3


50  

The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.

我发现的最佳解决方案(对于一个本应在框架中解决的令人沮丧的问题)与vaychick的方案类似。

Just set number of lines to 0 in either IB or code

在IB或代码中,将行数设置为0。

myLabel.numberOfLines = 0;

This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:

这将显示所需的行,但将重新定位标签,使其水平居中(使1行和3行标签对齐到它们的水平位置)。修复添加:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;

#4


31  

Use this to have multiple lines of text in UILabel:

使用它在UILabel中有多行文本:

textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

Swift:

迅速:

textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0

#5


20  

myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];

#6


15  

If you have to use the:

如果你必须使用:

myLabel.numberOfLines = 0;

property you can also use a standard line break ("\n"), in code, to force a new line.

属性还可以在代码中使用标准的换行符(“\n”)强制执行新行。

#7


13  

You can use \r to go to next line while filling up the UILabel using NSString.

使用NSString填充UILabel时,可以使用\r切换到下一行。

UILabel * label;


label.text = [NSString stringWithFormat:@"%@ \r %@",@"first line",@"seconcd line"];

#8


12  

lets try this

让我们试试这个

textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated     
textLabel.numberOfLines = 0;                          

#9


10  

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

The solution above does't work in my case. I'm doing like this:

上面的解决方案对我来说行不通。我做的是这样的:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // ...

    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap];
    return size.height + 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        // ...
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.font = [UIFont fontWithName:@"Georgia-Bold" size:18.0];
    }

    // ...

    UILabel *textLabel = [cell textLabel];
    CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0]
                                        constrainedToSize:CGSizeMake(240.0, 480.0)
                                            lineBreakMode:UILineBreakModeWordWrap];

    cell.textLabel.frame = CGRectMake(0, 0, size.width + 20, size.height + 20);

    //...
}

#10


8  

Use story borad : select the label to set number of lines to zero......Or Refer this

使用story borad:选择标签将行数设置为0…或参考这

UILabel中的多行文本

#11


6  

UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;

helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;

For some reasons its not working for me in iOS 6 not sure why. Tried it with and without attributed text. Any suggestions.

出于某些原因,它在ios6中不为我工作不确定原因。尝试使用和不使用带属性文本。任何建议。

#12


5  

Try using this code:

lblName.numberOfLines = 0;
[lblName sizeToFit];

#13


3  

you should try this:

你应该试试这个:

-(CGFloat)dynamicLblHeight:(UILabel *)lbl
{
    CGFloat lblWidth = lbl.frame.size.width;
    CGRect lblTextSize = [lbl.text boundingRectWithSize:CGSizeMake(lblWidth, MAXFLOAT)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                            attributes:@{NSFontAttributeName:lbl.font}
                                               context:nil];
    return lblTextSize.size.height;
}

#14


3  

These things helped me

这些事情帮助我

Change these properties of UILabel

改变UILabel的这些属性

label.numberOfLines = 0;
label.adjustsFontSizeToFitWidth = NO;
label.lineBreakMode = NSLineBreakByWordWrapping;

And while giving input String use \n to display different words in different lines.

在输入字符串时,使用\n以不同的行显示不同的单词。

Example :

例子:

 NSString *message = @"This \n is \n a demo \n message for \n *" ;

#15


3  

Swift 3
Set number of lines zero for dynamic text information, it will be useful for varying text.

Swift 3对动态文本信息的行数为0,对于不同的文本是有用的。

var label = UILabel()
let stringValue = "A label\nwith\nmultiline text."
label.text = stringValue
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
label.minimumScaleFactor = 0.8 . // It is not required but nice to have a minimum scale factor to fit text into label frame

UILabel中的多行文本

#16


2  

UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];

#17


2  

You can do that via the Storyboard too:

你也可以通过故事板来实现:

  1. Select the Label on the view controller
  2. 选择视图控制器上的标签
  3. In the Attribute Inspector, increase the value of the Line option (Press Alt+Cmd+4 to show Attributes Inspector)
  4. 在属性检查器中,增加行选项的值(按Alt+Cmd+4显示属性检查器)
  5. Double click the Label in the view controller and write or paste your text
  6. 双击视图控制器中的标签并写入或粘贴文本
  7. Resize the Label and/or increase the font size so that the whole text could be shown
  8. 调整标签大小和/或增加字体大小,以便显示整个文本

#18


2  

I agree with Jarred Olson, NSLineBreakByWordWrapping is default. I added property sizeToFit like the guide of Gurumoorthy Arumugam to fix it.

我同意Jarred Olson的观点,nslinebreakbywordwrapper是默认值。我添加了一些属性,比如Gurumoorthy Arumugam的向导来修复它。

If you want the font inside your label to adjust itself to fit into the boundaries of the label. You can use :

如果您想要标签内的字体调整自己以适应标签的边界。您可以使用:

textLabel.adjustsFontSizeToFitWidth = YES;

Thanks all.

谢谢所有。

#19


1  

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";

#20


1  

Already answered, but you can do it manually in the storyboard too. Under Attributes Inspector for the Label, you can change Line Breaks to Word Wrap (or character wrap).

已经回答了,但是您也可以在故事板中手动完成。在标签的属性检查器下,可以将换行符更改为换行(或换行)。

#21


1  

In this function pass string that you want to assign in label and pass font size in place of self.activityFont and pass label width in place of 235, now you get label height according to your string. it will work fine.

在此函数中,传递要在标签中指定的字符串,并传递字体大小代替self。activityFont和pass标签宽度为235,现在你可以根据你的字符串获得标签高度。它会正常工作。

-(float)calculateLabelStringHeight:(NSString *)answer
{
    CGRect textRect = [answer boundingRectWithSize: CGSizeMake(235, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.activityFont} context:nil];
    return textRect.size.height;

}

#22


1  

Set below either in code or in storyboard itself

在代码或故事板本身中设置。

Label.lineBreakMode = NSLineBreakByWordWrapping; Label.numberOfLines = 0;

标签。lineBreakMode = NSLineBreakByWordWrapping;标签。numberOfLines = 0;

and please don't forget to set left, right, top and bottom constraints for label otherwise it won't work.

请不要忘记为标签设置左,右,上和下的约束否则它不会工作。

#23


0  

On C#, this worked for me inside UITableViewCell.

在c#上,这在UITableViewCell中为我工作。

        UILabel myLabel = new UILabel();
        myLabel.Font = UIFont.SystemFontOfSize(16);
        myLabel.Lines = 0;
        myLabel.TextAlignment = UITextAlignment.Left;
        myLabel.LineBreakMode = UILineBreakMode.WordWrap;
        myLabel.MinimumScaleFactor = 1;
        myLabel.AdjustsFontSizeToFitWidth = true;

       myLabel.InvalidateIntrinsicContentSize();
       myLabel.Frame = new CoreGraphics.CGRect(20, mycell.ContentView.Frame.Y + 20, cell.ContentView.Frame.Size.Width - 40, mycell.ContentView.Frame.Size.Height);
       myCell.ContentView.AddSubview(myLabel);

I think the point here is:-

我想这里的重点是:-

            myLabel.TextAlignment = UITextAlignment.Left;
            myLabel.LineBreakMode = UILineBreakMode.WordWrap;
            myLabel.MinimumScaleFactor = 1;
            myLabel.AdjustsFontSizeToFitWidth = true;

#24


-1  

This code is returning size height according to text

此代码根据文本返回大小高度

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
 {
    CGFloat result = font.pointSize+4;
    if (text) 
{
        CGSize size;

        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);
        result = MAX(size.height, result); //At least one row
    }
    return result;
}

#1


737  

I found a solution.

我找到了一个解决方案。

One just has to add the following code:

只需添加以下代码:

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0 

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

Restored old answer (for reference and devs willing to support iOS below 6.0):

恢复旧答案(供参考和开发人员支持iOS 6.0以下):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

On the side: both enum values yield to 0 anyway.

另一方面:无论如何,这两个枚举值的收益率都为0。

#2


124  

In IB, set number of lines to 0 (allows unlimited lines)

在IB中,将行数设置为0(允许无限行)

When typing within the text field using IB, use "alt-return" to insert a return and go to the next line (or you can copy in text already separated out by lines).

当使用IB在文本字段中输入时,使用“alt-return”插入一个返回并转到下一行(或者您可以在用行分隔的文本中复制)。

#3


50  

The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.

我发现的最佳解决方案(对于一个本应在框架中解决的令人沮丧的问题)与vaychick的方案类似。

Just set number of lines to 0 in either IB or code

在IB或代码中,将行数设置为0。

myLabel.numberOfLines = 0;

This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:

这将显示所需的行,但将重新定位标签,使其水平居中(使1行和3行标签对齐到它们的水平位置)。修复添加:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;

#4


31  

Use this to have multiple lines of text in UILabel:

使用它在UILabel中有多行文本:

textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

Swift:

迅速:

textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0

#5


20  

myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];

#6


15  

If you have to use the:

如果你必须使用:

myLabel.numberOfLines = 0;

property you can also use a standard line break ("\n"), in code, to force a new line.

属性还可以在代码中使用标准的换行符(“\n”)强制执行新行。

#7


13  

You can use \r to go to next line while filling up the UILabel using NSString.

使用NSString填充UILabel时,可以使用\r切换到下一行。

UILabel * label;


label.text = [NSString stringWithFormat:@"%@ \r %@",@"first line",@"seconcd line"];

#8


12  

lets try this

让我们试试这个

textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated     
textLabel.numberOfLines = 0;                          

#9


10  

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

The solution above does't work in my case. I'm doing like this:

上面的解决方案对我来说行不通。我做的是这样的:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // ...

    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap];
    return size.height + 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        // ...
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.font = [UIFont fontWithName:@"Georgia-Bold" size:18.0];
    }

    // ...

    UILabel *textLabel = [cell textLabel];
    CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0]
                                        constrainedToSize:CGSizeMake(240.0, 480.0)
                                            lineBreakMode:UILineBreakModeWordWrap];

    cell.textLabel.frame = CGRectMake(0, 0, size.width + 20, size.height + 20);

    //...
}

#10


8  

Use story borad : select the label to set number of lines to zero......Or Refer this

使用story borad:选择标签将行数设置为0…或参考这

UILabel中的多行文本

#11


6  

UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;

helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;

For some reasons its not working for me in iOS 6 not sure why. Tried it with and without attributed text. Any suggestions.

出于某些原因,它在ios6中不为我工作不确定原因。尝试使用和不使用带属性文本。任何建议。

#12


5  

Try using this code:

lblName.numberOfLines = 0;
[lblName sizeToFit];

#13


3  

you should try this:

你应该试试这个:

-(CGFloat)dynamicLblHeight:(UILabel *)lbl
{
    CGFloat lblWidth = lbl.frame.size.width;
    CGRect lblTextSize = [lbl.text boundingRectWithSize:CGSizeMake(lblWidth, MAXFLOAT)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                            attributes:@{NSFontAttributeName:lbl.font}
                                               context:nil];
    return lblTextSize.size.height;
}

#14


3  

These things helped me

这些事情帮助我

Change these properties of UILabel

改变UILabel的这些属性

label.numberOfLines = 0;
label.adjustsFontSizeToFitWidth = NO;
label.lineBreakMode = NSLineBreakByWordWrapping;

And while giving input String use \n to display different words in different lines.

在输入字符串时,使用\n以不同的行显示不同的单词。

Example :

例子:

 NSString *message = @"This \n is \n a demo \n message for \n *" ;

#15


3  

Swift 3
Set number of lines zero for dynamic text information, it will be useful for varying text.

Swift 3对动态文本信息的行数为0,对于不同的文本是有用的。

var label = UILabel()
let stringValue = "A label\nwith\nmultiline text."
label.text = stringValue
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
label.minimumScaleFactor = 0.8 . // It is not required but nice to have a minimum scale factor to fit text into label frame

UILabel中的多行文本

#16


2  

UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];

#17


2  

You can do that via the Storyboard too:

你也可以通过故事板来实现:

  1. Select the Label on the view controller
  2. 选择视图控制器上的标签
  3. In the Attribute Inspector, increase the value of the Line option (Press Alt+Cmd+4 to show Attributes Inspector)
  4. 在属性检查器中,增加行选项的值(按Alt+Cmd+4显示属性检查器)
  5. Double click the Label in the view controller and write or paste your text
  6. 双击视图控制器中的标签并写入或粘贴文本
  7. Resize the Label and/or increase the font size so that the whole text could be shown
  8. 调整标签大小和/或增加字体大小,以便显示整个文本

#18


2  

I agree with Jarred Olson, NSLineBreakByWordWrapping is default. I added property sizeToFit like the guide of Gurumoorthy Arumugam to fix it.

我同意Jarred Olson的观点,nslinebreakbywordwrapper是默认值。我添加了一些属性,比如Gurumoorthy Arumugam的向导来修复它。

If you want the font inside your label to adjust itself to fit into the boundaries of the label. You can use :

如果您想要标签内的字体调整自己以适应标签的边界。您可以使用:

textLabel.adjustsFontSizeToFitWidth = YES;

Thanks all.

谢谢所有。

#19


1  

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";

#20


1  

Already answered, but you can do it manually in the storyboard too. Under Attributes Inspector for the Label, you can change Line Breaks to Word Wrap (or character wrap).

已经回答了,但是您也可以在故事板中手动完成。在标签的属性检查器下,可以将换行符更改为换行(或换行)。

#21


1  

In this function pass string that you want to assign in label and pass font size in place of self.activityFont and pass label width in place of 235, now you get label height according to your string. it will work fine.

在此函数中,传递要在标签中指定的字符串,并传递字体大小代替self。activityFont和pass标签宽度为235,现在你可以根据你的字符串获得标签高度。它会正常工作。

-(float)calculateLabelStringHeight:(NSString *)answer
{
    CGRect textRect = [answer boundingRectWithSize: CGSizeMake(235, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.activityFont} context:nil];
    return textRect.size.height;

}

#22


1  

Set below either in code or in storyboard itself

在代码或故事板本身中设置。

Label.lineBreakMode = NSLineBreakByWordWrapping; Label.numberOfLines = 0;

标签。lineBreakMode = NSLineBreakByWordWrapping;标签。numberOfLines = 0;

and please don't forget to set left, right, top and bottom constraints for label otherwise it won't work.

请不要忘记为标签设置左,右,上和下的约束否则它不会工作。

#23


0  

On C#, this worked for me inside UITableViewCell.

在c#上,这在UITableViewCell中为我工作。

        UILabel myLabel = new UILabel();
        myLabel.Font = UIFont.SystemFontOfSize(16);
        myLabel.Lines = 0;
        myLabel.TextAlignment = UITextAlignment.Left;
        myLabel.LineBreakMode = UILineBreakMode.WordWrap;
        myLabel.MinimumScaleFactor = 1;
        myLabel.AdjustsFontSizeToFitWidth = true;

       myLabel.InvalidateIntrinsicContentSize();
       myLabel.Frame = new CoreGraphics.CGRect(20, mycell.ContentView.Frame.Y + 20, cell.ContentView.Frame.Size.Width - 40, mycell.ContentView.Frame.Size.Height);
       myCell.ContentView.AddSubview(myLabel);

I think the point here is:-

我想这里的重点是:-

            myLabel.TextAlignment = UITextAlignment.Left;
            myLabel.LineBreakMode = UILineBreakMode.WordWrap;
            myLabel.MinimumScaleFactor = 1;
            myLabel.AdjustsFontSizeToFitWidth = true;

#24


-1  

This code is returning size height according to text

此代码根据文本返回大小高度

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
 {
    CGFloat result = font.pointSize+4;
    if (text) 
{
        CGSize size;

        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);
        result = MAX(size.height, result); //At least one row
    }
    return result;
}