465

有没有办法让多行文本UILabel像这样,UITextView或者我应该使用第二行?

4

26 回答 26

828

将换行模式设置为自动换行,将行数设置为0

// Swift
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0

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

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

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

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

另一方面:两个枚举值都屈服于0

于 2009-06-13T07:43:45.573 回答
144

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

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

于 2009-06-14T09:27:39.450 回答
55

我找到的最佳解决方案(对于本来应该在框架中解决的令人沮丧的问题)类似于 vaychick 的。

只需在 IB 或代码中将行数设置为 0

myLabel.numberOfLines = 0;

这将显示所需的行,但会重新定位标签,使其水平居中(以便 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;
于 2011-06-29T09:29:40.483 回答
36

使用它在 中包含多行文本UILabel

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

迅速:

textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0
于 2013-12-05T10:06:32.080 回答
23
myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];
于 2012-12-19T06:21:53.017 回答
17

如果你必须使用:

myLabel.numberOfLines = 0;

属性,您还可以在代码中使用标准换行符("\n")来强制换行。

于 2011-08-22T14:43:37.250 回答
15

您可以在填写using时使用\r转到下一行。UILabelNSString

UILabel * label;


label.text = [NSString stringWithFormat:@"%@ \r %@",@"first line",@"seconcd line"];
于 2012-11-16T05:57:23.037 回答
14

让我们试试这个

textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated     
textLabel.numberOfLines = 0;                          
于 2014-02-06T09:29:15.523 回答
11
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

上面的解决方案在我的情况下不起作用。我正在这样做:

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

    //...
}
于 2011-04-14T08:18:14.830 回答
9

Swift 3
将动态文本信息的行数设置为零,这对于改变文本很有用。

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

在此处输入图像描述

于 2017-06-09T13:57:32.957 回答
8

使用故事板:选择标签以将行数设置为零……或参考此

在此处输入图像描述

于 2016-05-25T07:54:03.250 回答
7

尝试使用这个:

lblName.numberOfLines = 0;
[lblName sizeToFit];
于 2014-05-20T06:02:20.483 回答
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;

由于某些原因,它在 iOS 6 中对我不起作用,不知道为什么。尝试使用和不使用属性文本。有什么建议么。

于 2013-08-21T19:41:52.990 回答
6

方法一:

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

现在像这样简单地调用

myLbl.lblFunction()//Replace your label name 

前任:

Import UIKit

class MyClassName: UIViewController {//For example this is your class. 

    override func viewDidLoad() {
    super.viewDidLoad()

        myLbl.lblFunction()//Replace your label name 

    }

}//After close of your class write this extension.

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

方法二:

以编程方式

yourLabel.numberOfLines = 0
yourLabel.lineBreakMode = .byWordWrapping//If you want word wraping
//OR
yourLabel.lineBreakMode = .byCharWrapping//If you want character wraping

方法三:

通过故事板

要显示多行设置 0(零),这将在您的标签中显示多行。

如果要显示 n 行,请设置 n。

请参见下面的屏幕。

在此处输入图像描述

如果要为标签设置最小字体大小单击自动收缩并选择最小字体大小选项

请参阅以下屏幕

在此处输入图像描述

这里设置最小字体大小

例如:9(在这张图片中)

如果您的标签当时有更多文本,您的标签文本将缩小到 9

在此处输入图像描述

于 2019-01-02T12:27:09.317 回答
3

这些东西帮助了我

更改 UILabel 的这些属性

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

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

例子 :

 NSString *message = @"This \n is \n a demo \n message for \n stackoverflow" ;
于 2017-09-08T06:41:27.363 回答
2
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];
于 2014-05-20T06:00:00.710 回答
2

你也可以通过 Storyboard 做到这一点:

  1. 选择视图控制器上的标签
  2. 在 Attribute Inspector 中,增加 Line 选项的值(按 Alt+Cmd+4 显示 Attributes Inspector)
  3. 双击视图控制器中的标签并写入或粘贴您的文本
  4. 调整标签大小和/或增加字体大小,以便显示整个文本
于 2014-05-21T18:08:03.007 回答
2

你应该试试这个:

-(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;
}
于 2015-08-14T12:29:28.287 回答
2

斯威夫特 4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

label.preferredMaxLayoutWidth = superview.bounds.size.width - 10 
于 2018-09-25T10:31:52.523 回答
1
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";
于 2014-05-19T06:29:55.477 回答
1

已经回答,但您也可以在情节提要中手动完成。在标签的属性检查器下,您可以将换行符更改为自动换行(或字符换行)。

于 2014-05-30T22:32:30.423 回答
1

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

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

}
于 2014-12-05T06:23:28.007 回答
1

在代码或情节提要本身中设置如下

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

并且请不要忘记为标签设置左、右、上和下约束,否则它将不起作用。

于 2017-01-17T09:34:45.520 回答
1

哦,2021年我被一个标签文本困了1小时无法换行,然后意识到我忘记设置标签的宽度,WTF。

let stepLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.lineBreakMode = .byWordWrapping
    label.numberOfLines = 0
    label.text = "Put your device and computer under same Wi-Fi network."
    
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    view.addSubview(stepLabel)

    NSLayoutConstraint.activate([
        stepLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        stepLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        stepLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7)
    ])
}
于 2021-08-03T05:21:21.600 回答
0

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

我认为这里的重点是:-

            myLabel.TextAlignment = UITextAlignment.Left;
            myLabel.LineBreakMode = UILineBreakMode.WordWrap;
            myLabel.MinimumScaleFactor = 1;
            myLabel.AdjustsFontSizeToFitWidth = true;
于 2018-05-17T06:22:10.480 回答
-2

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

+ (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;
}
于 2015-01-22T11:35:43.950 回答