我有一个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()
Run Code Online (Sandbox Code Playgroud)
这对我来说无论如何都不适合!我总是只看到一行文字UILabel.我究竟做错了什么?
我绝对需要文本内容可变.
Ami*_*ole 27
我通过添加自动布局约束来解决问题:

但我对此并不满意.经过了大量的试验和错误,无法理解为什么会这样.
另外,我必须添加到titleLabel.numberOfLines = 0我的使用ViewController
Aru*_*pta 21
如果您正在寻找基于其文本精确占据空间的多行动态文本标签,这是更好的方法.
没有sizeToFit,使用preferredMaxLayoutWidth
以下是它的工作原理.
让我们设置项目.在Single View应用程序和Storyboard中添加UILabel和UIButton.将UILabel的约束定义为以下快照:
将Label属性设置为如下图像:
将约束添加到UIButton.确保UILabel和UIButton之间的垂直间距为100
现在将UILabel的尾随约束的优先级设置为749
现在将UILabel的Horizontal Content Hugging和Horizontal Content Compression属性设置为750和748
下面是我的控制器类.您必须将故事板中的UILabel属性和Button操作连接到viewcontroller类.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["jackson 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.
}
}
Run Code Online (Sandbox Code Playgroud)
而已.这将根据其内容自动调整UILabel的大小,您也可以看到UIButton也相应调整.
La *_*sse 20
我知道它有点老了但是我最近调查了它:
let l = UILabel()
l.numberOfLines = 0
l.lineBreakMode = .ByWordWrapping
l.text = "BLAH BLAH BLAH BLAH BLAH"
l.frame.size.width = 300
l.sizeToFit()
Run Code Online (Sandbox Code Playgroud)
首先将numberOfLines属性设置为0,以便设备理解您不关心它需要多少行.然后指定您最喜欢的BreakMode然后需要在sizeToFit()方法之前设置宽度.然后标签知道它必须符合指定的宽度
Bhu*_*tre 17
它应该工作.试试这个
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);
Run Code Online (Sandbox Code Playgroud)
使用Xcode中的图形用户界面(GUI),您可以执行以下操作:
- 转到“
Attribute Inspector”并将Lines值设置为0。默认情况下,它设置为1。- 通过点击,标签文本可以多行书写
option + return。
- 现在,进入“
Size Inspector”和设置width,height,X和Yposition标签。
就这样。