简体   繁体   English

设置为自动换行时如何获取UILabel文本的实际宽度

[英]How to get actual width of UILabel text when set to word wrap

I have the following code to set up a UILabel: 我有以下代码来设置UILabel:

let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.preferredMaxLayoutWidth = maxWidth

label.text = "String that is long enough to cause word wrap."

label.sizeToFit()
self.view.addSubview(label)

The result that I need is for the label to wrap the text as it would once it reaches label.preferredMaxLayoutWidth then actually size itself to just wide enough to fit the wrapped text. 我需要的结果是标签将文本包装起来,就像到达label.preferredMaxLayoutWidth然后将其自身的大小调整到足以适合包装文本的宽度。 Here's a diagram to illustrate: 这是说明的图: 在此处输入图片说明

The red box's width is equal to label.preferredMaxLayoutWidth and that is the actual size I am getting with my code above. 红色框的宽度等于label.preferredMaxLayoutWidth ,这是我在上面的代码中获得的实际大小。 The black box is the size that I would like it to be. 黑匣子是我想要的大小。 Whether the label was sized to the red or black, the word wrapping would be the same. 无论标签的大小是红色还是黑色,自动换行都是相同的。

So, how can I resize my label to be the smallest possible width while maintaining the current word wrap? 因此,如何在保持当前自动换行的同时将标签的大小调整为最小可能的宽度?

Edit: 编辑:

Although constraints might be the usual option, in my case, I don't think it is because I am sizing my superview according to the resulting size of this label. 尽管约束可能是通常的选择,但就我而言,我不认为这是因为我正在根据此标签的结果大小来确定超级视图的大小。

Ok, I just figured it out. 好吧,我只是想通了。 @rmaddy was correct in the question's comments above. @rmaddy在上述问题的评论中是正确的。 I had seen boundingRectWithSize:options:attributes:context: before asking the question, but had issues figuring it out in swift. 在问这个问题之前,我已经看过boundingRectWithSize:options:attributes:context: :,但是遇到了迅速解决问题的问题。 But now I've got it. 但是现在我明白了。 Here is my updated code: 这是我更新的代码:

let label = UILabel() 让标签= UILabel()

    let text = "String that is long enough to cause word wrap."
    let rect = text.boundingRect(with: CGSize(width: maxDesiredWidth, height:CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: nil, context: nil)

    label.numberOfLines = 0
    label.textAlignment = .center
    label.lineBreakMode = .byWordWrapping
    label.frame = rect

    label.text = text

    label.sizeToFit()
    self.view.addSubview(label)

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

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