简体   繁体   English

UILabel 中的多行文本

[英]Multiple lines of text in UILabel

有没有办法像UITextView一样在UILabel有多行文本,还是应该使用第二行?

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): 恢复了旧答案(供参考和愿意在6.0以下支持iOS的开发人员使用):

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

On the side: both enum values yield to 0 anyway. 从侧面看:两个枚举值都将变为0

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”插入一个返回符并转到下一行(或者您可以复制已经由行分隔的文本)。

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). 这将显示所需的行,但将重新放置标签,使其水平居中(以便1行和3行标签在其水平位置对齐)。 To fix that add: 要解决此问题,请执行以下操作:

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;

Use this to have multiple lines of text in UILabel : 使用它可以在UILabel包含多行文本:

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

Swift: 迅速:

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

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")强制换行。

You can use \\r to go to next line while filling up the UILabel using NSString . 您可以使用\\r转到下一行,同时使用NSString填充UILabel

UILabel * label;


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

lets try this 让我们尝试一下

textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated     
textLabel.numberOfLines = 0;                          
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);

    //...
}

Use story borad : select the label to set number of lines to zero...... Or Refer this 使用Story Borad:选择标签以将行数设置为零…… 或参考此

在此处输入图片说明

Swift 3 迅捷3
Set number of lines zero for dynamic text information, it will be useful for varying text. 对于动态文本信息,将行数设置为零,这对于更改文本很有用。

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 *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. 由于某些原因,它在iOS 6中对我不起作用,不确定原因。 Tried it with and without attributed text. 尝试使用带属性文本和不带属性文本的情况。 Any suggestions. 有什么建议么。

Try using this: 尝试使用此:

lblName.numberOfLines = 0;
[lblName sizeToFit];

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

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 stackoverflow" ;
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];

You can do that via the Storyboard too: 您也可以通过情节提要进行此操作:

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

Method 1: 方法1:

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

Now call simply like this 现在这样简单地打电话

myLbl.lblFunction()//Replace your label name 

EX: 例如:

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

Method 2: 方法2:

Programmatically 以编程方式

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

Method 3: 方法3:

Through Story board 通过故事板

To display multiple lines set 0(Zero), this will display more than one line in your label. 要显示多行设置为0(零),这将在标签中显示多行。

If you want to display n lines, set n. 如果要显示n行,请设置n。

See below screen. 请参阅以下屏幕。

在此处输入图片说明

If you want to set minimum font size for label Click Autoshrink and Select Minimum Font Size option 如果要设置标签的最小字体大小,请单击“自动收缩”,然后选择“最小字体大小”选项

See below screens 请参阅以下屏幕

在此处输入图片说明

Here set minimum font size 此处设置最小字体

EX: 9 (In this image) EX:9(在此图像中)

If your label get more text at that time your label text will be shrink upto 9 如果您的标签当时有更多文字,您的标签文字将缩小到9

在此处输入图片说明

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

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). 在“标签的属性检查器”下,可以将“换行符”更改为“自动换行”(或“自动换行”)。

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. 在此函数中,您要在标签中分配的传递字符串并通过字体大小代替self.activityFont并在235中传递标签宽度,现在您将根据字符串获得标签高度。 it will work fine. 它将正常工作。

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

}

Set below either in code or in storyboard itself 在代码或情节提要中设置以下内容

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

and please don't forget to set left, right, top and bottom constraints for label otherwise it won't work. 并且请不要忘记为标签设置左,右,顶部和底部约束,否则它将无法正常工作。

Swift 4: 斯威夫特4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

label.preferredMaxLayoutWidth = superview.bounds.size.width - 10 

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;

Oh, in 2021 I'm trapped by a label text unable to change lines for 1 hour, then realize I forget to set label's width, WTF.哦,在 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)
    ])
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM