ios 如何设置自适应多行 UILabel 文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24134905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:45:26  来源:igfitidea点击:

How do I set adaptive multiline UILabel text?

iosswift

提问by Amit Erandole

I have a UILabelnamed titleLabelin my storyboardnib set to its default height. I want it to programaticallyexpand in height to fit it's content. Here is what I have tried so far:

我的故事板笔尖中有一个UILabel命名为默认高度。我希望它以编程方式扩展高度以适合其内容。这是我迄今为止尝试过的:titleLabel

// just setting content
titleLabel.text = "You don't always know what you are getting with mass-market cloud computing services. But with SimpliCompute, the picture is clear. SimpliCompute gives you powerful virtual servers you can deploy using just your web browser. That's enterprise grade technology you can deploy and control on-the-fly."

titleLabel.numberOfLines = 0

titleLabel.preferredMaxLayoutWidth = 700

titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

titleLabel.sizeToFit()

None of this works for me in any combination! I always only see one line of text in my UILabel. What am I doing wrong?

在任何组合中,这些都不适合我!我总是只在我的UILabel. 我究竟做错了什么?

I absolutely need the text content to be variable.

我绝对需要文本内容是可变的。

采纳答案by Amit Erandole

I kind of got things working by adding auto layout constraints:

我通过添加自动布局约束来使事情工作:

auto layout contraints

自动布局约束

But I am not happy with this. Took a lot of trial and error and couldn't understand why this worked.

但我对此并不满意。进行了大量的反复试验,无法理解为什么会这样。

Also I had to add to use titleLabel.numberOfLines = 0in my ViewController

我还必须添加以titleLabel.numberOfLines = 0在我的ViewController

回答by Arun Gupta

This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.

如果您正在寻找根据文本准确占用空间的多行动态文本标签,这是更好的方法。

No sizeToFit, preferredMaxLayoutWidth used

没有 sizeToFit,使用了 preferredMaxLayoutWidth

Below is how it will work.

下面是它将如何工作。

enter image description here

在此处输入图片说明

Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:

让我们设置项目。以单视图应用程序为例,在 Storyboard 中添加一个 UILabel 和一个 UIButton。定义 UILabel 的约束,如下图所示:

enter image description here

在此处输入图片说明

Set the Label properties as below image:

如下图设置标签属性:

enter image description here

在此处输入图片说明

Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton

将约束添加到 UIButton。确保 UILabel 和 UIButton 之间的垂直间距为 100

enter image description here

在此处输入图片说明

Now set the priority of the trailing constraint of UILabel as 749

现在将 UILabel 的尾随约束的优先级设置为 749

enter image description here

在此处输入图片说明

Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748

现在将 UILabel 的 Horizo​​ntal Content Hugging 和 Horizo​​ntal Content Compression 属性设置为 750 和 748

enter image description here

在此处输入图片说明

Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.

下面是我的控制器类。您必须将 UILabel 属性和 Button 动作从故事板连接到视图控制器类。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["Hymanson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]


@IBAction func updateLabelText(sender: UIButton) {
    if count > 3 {
        count = 0
    }
    textLabel.text = items[count]
    count = count + 1
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //self.textLabel.sizeToFit()
    //self.textLabel.preferredMaxLayoutWidth = 500
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.

就是这样。这将根据其内容自动调整 UILabel 的大小,您还可以看到 UIButton 也相应地进行了调整。

回答by La masse

I know it's a bit old but since I recently looked into it :

我知道它有点旧,但因为我最近研究过它:

let l = UILabel()
l.numberOfLines = 0
l.lineBreakMode = .ByWordWrapping
l.text = "BLAH BLAH BLAH BLAH BLAH"
l.frame.size.width = 300
l.sizeToFit()

First set the numberOfLines property to 0 so that the device understands you don't care how many lines it needs. Then specify your favorite BreakMode Then the width needs to be set before sizeToFit() method. Then the label knows it must fit in the specified width

首先将 numberOfLines 属性设置为 0,以便设备理解您不关心它需要多少行。然后指定你最喜欢的 BreakMode 那么宽度需要在 sizeToFit() 方法之前设置。然后标签知道它必须适合指定的宽度

回答by Bhumeshwer katre

It should work. Try this

它应该工作。尝试这个

var label:UILabel = UILabel(frame: CGRectMake(10
    ,100, 300, 40));
label.textAlignment = NSTextAlignment.Center;
label.numberOfLines = 0;
label.font = UIFont.systemFontOfSize(16.0);
label.text = "First label\nsecond line";
self.view.addSubview(label);

回答by Mukesh Chapagain

With Graphical User Interface (GUI) in Xcode, you can do the following:

使用 Xcode 中的图形用户界面 (GUI),您可以执行以下操作:

  • Go to "Attribute Inspector" and set Linesvalue to 0. By default, it is set to 1.
  • The Label text can be written in multi-line by hitting option + return.
  • 转到“ Attribute Inspector”并将Lines值设置为0。默认情况下,它设置为1
  • 可以通过点击 将标签文本写成多行option + return

enter image description here

在此处输入图片说明

  • Now, go to "Size Inspector" and set the width, height, X& Ypositionof the Label.
  • 现在,转到“ Size Inspector”并设置标签的width, height, X& Yposition

enter image description here

在此处输入图片说明

That's all.

就这样。

回答by user1023102

Programmatically, Swift

以编程方式,Swift

label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.titleView.numberOfLines = 2

回答by eharo2

Programmatically in Swift 5 with Xcode 10.2

使用 Xcode 10.2 在 Swift 5 中以编程方式

Building on top of @La masse's solution, but using autolayout to support rotation

建立在@La masse 的解决方案之上,但使用自动布局来支持旋转

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

为视图的位置设置锚点(左、上、centerY、centerX 等)。您还可以使用提供的 UIScreen 扩展(以支持旋转)动态设置宽度锚点或设置 frame.width

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()

If setting frame.width dynamically using UIScreen:

如果使用 UIScreen 动态设置 frame.width:

extension UIScreen {   // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        }
        return width
    }
}