ChatGPT解决这个技术问题 Extra ChatGPT

UILabel 中的多行文本

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

请注意,UILineBreakModeWordWrap 在 iOS 6 中已被弃用。您现在应该使用 NSLineBreakByWordWrapping = 0 请参阅文档here

p
pkamb

将换行模式设置为自动换行,将行数设置为 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


UILineBreakModeWordWrap 实际上是默认值,因此您不需要第一行。
对于使用 swift 的用户:cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrappingcell.textLabel?.numberOfLines = 0
感谢您还提供 Xamarin-Code。自动完成不起作用,因为他们选择缩写该属性... +1
我同意 Jarred Olson 的观点,NSLineBreakByWordWrapping 是默认设置。我像 Gurumoorthy Arumugam 的指南一样添加了属性 sizeToFit 来修复它。如果您希望标签内的字体自行调整以适应标签的边界。您可以使用:textLabel.adjustsFontSizeToFitWidth = YES;谢谢大家。
@JarredOlson 文档说“此属性默认设置为 byTruncatingTail。”
K
Kendall Helmstetter Gelner

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

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


[因为他故意挖掘了一个超过一年的线程......] 我有时希望我能在 IB 中做的一件事是输入没有嵌入换行符的文本,设置 UILineBreakModeWordWrap 和 numberOfLines = 0,然后将标签设为 auto - 自动调整高度,同时仍在 IB 中进行设计。我正在考虑将视图大小调整为横向的情况,其中标签中的换行符可能会出现问题。或者……我可能在滥用 IB!也许让标签在 IB 中自动调整大小会导致比它解决的问题更多? (此外,此时无论如何您都不能调用 sizeToFit。)
我从 UILabel 的文档中得到的“0”东西,来自一个使用 Interface Builder 多年的朋友的 alt-return。
+1 是唯一提到“alt-return”的答案。特别是“ctrl-return”似乎会起作用,但不会。
T
Tieme

我找到的最佳解决方案(对于本来应该在框架中解决的令人沮丧的问题)类似于 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;

在您和@Ilya Suzdalnitski 的帮助下解决我的问题。非常感谢。
T
Taiwosam

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

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

迅速:

textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0

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

M
Matt Wilko

如果你必须使用:

myLabel.numberOfLines = 0;

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


p
prajul

您可以使用 \r 转到下一行,同时使用 NSString 填写 UILabel

UILabel * label;


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

l
lal

让我们试试这个

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

这也可以在整个 IB 'Lines' 属性中设置为 UILabel 上的 0。
b
bartolo-otrit
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);

    //...
}

K
Krunal

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

https://i.stack.imgur.com/ej8F9.png


谢谢Krunal,它对我有用!
C
Community

使用故事板:选择标签以将行数设置为零......Or Refer this

https://i.stack.imgur.com/CYBQL.png


P
Pang

尝试使用这个:

lblName.numberOfLines = 0;
[lblName sizeToFit];

当 numberOfLine 不为 0 时 sizeToFit 不起作用。这很有趣。
A
Adrian P
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 中对我不起作用,不知道为什么。尝试使用和不使用属性文本。有什么建议么。


N
Naresh

方法一:

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。

请参见下面的屏幕。

https://i.stack.imgur.com/HHEm6.png

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

请参阅以下屏幕

https://i.stack.imgur.com/hGDFi.png

这里设置最小字体大小

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

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

https://i.stack.imgur.com/cHoi7.png


i
iPhoneDeveloper

这些东西帮助了我

更改 UILabel 的这些属性

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

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

例子 :

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

E
Eric Aya

斯威夫特 4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

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

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

不要忘记添加:[labelName setLineBreakMode:NSLineBreakByWordWrapping];
O
OsLivon

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

选择视图控制器上的标签 在属性检查器中,增加 Line 选项的值(按 Alt+Cmd+4 显示属性检查器) 双击视图控制器中的标签并写入或粘贴文本调整标签大小和/或增加字体大小,以便显示整个文本


并将 Lines 设置为 0,否则只会显示可以放入指定行数的文本,其他将被省略。
P
Pritesh

你应该试试这个:

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

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

F
Fleija

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


M
McDowell

在此函数中,传递您要在标签中分配的字符串并传递字体大小代替 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;

}

g
garg

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

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

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


到处都说将自动换行和行数设置为 0。但我的仍然没有换行。设置左、上、下和右约束使其环绕。
C
ChuckZHB

哦,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)
    ])
}

A
Alvin George

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

M
Majid Bashir

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

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