有没有办法在UILabel中像UITextView中那样有多行文本或者我应该用第二行代替?


当前回答

我找到的最好的解决方案(解决一个本来应该在框架中解决的令人沮丧的问题)与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;

其他回答

当使用NSString填充UILabel时,您可以使用\r转到下一行。

UILabel * label;


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

哦,在2021年,我被一个标签文本困住了,一个小时都不能换行,然后意识到我忘记设置标签的宽度,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)
    ])
}

你也可以通过Storyboard来实现:

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

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

我找到的最好的解决方案(解决一个本来应该在框架中解决的令人沮丧的问题)与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;