多行UILabel没有正确包装单词

时间:2017-03-02 17:15:54

标签: ios swift xcode swift3 uilabel

我在调整字体大小以适应标签而不分割任何单词时遇到问题。  我有一个标签,它将根据字符串数组动态更改其内容。  标签可以有任意数量的行。我想要的是字体大小尽可能大,同时适合标签而不是分割任何单词。  我在故事板上做了很大的字体大小。  标签使用自动布局放置在视图上。

例如,对于字符串“Most definitely”,如果我使用此代码:

 answerLabel.numberOfLines = 0
 answerLabel.adjustsFontSizeToFitWidth = true
 answerLabel.lineBreakMode = .byTruncatingTail

我得到的字符串如下: 大多数(第1行) Definitel(第2行)y(第3行)

如果另一方面我做

    answerLabel.numberOfLines = 0
    answerLabel.adjustsFontSizeToFitWidth = true
    answerLabel.lineBreakMode = .byWordWrapping

我在大字母中得到一个字符串“Mo”

显然,在这种情况下我正在寻找的是Most(第1行)肯定(第2行)。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Swift 3
为动态文本信息设置零行数,它对于改变文本非常有用。

var label = UILabel()
let stringValue = "Multiline UILabel not wrapping words correctly"
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

使用Interface Builder:

enter image description here