我想知道当numberOfLines设置为1时,为什么我的UILabel没有正确调整字体大小。我有一个操场,代码如下:

import UIKit
import PlaygroundSupport

let labelFrame = CGRect(x: 0, y: 0, width: 100, height: 100)
let label = UILabel(frame: labelFrame)
label.backgroundColor = .lightGray
label.text = "Something that's pretty long"

label.baselineAdjustment = .alignCenters
label.adjustsFontSizeToFitWidth = true

label.numberOfLines = 1
label.minimumScaleFactor = 0.1

let frame = CGRect(x: 0, y: 0, width: 300, height: 300)
let view = UIView(frame: frame)
view.backgroundColor = .white

view.addSubview(label)

PlaygroundPage.current.liveView = view

这就是结果ios - AdjustsFontSizeToFitWidth的异常行为-LMLPHP
但是,当我将numberOfLines更改为2时,字体会像预期的那样缩小:
import UIKit
import PlaygroundSupport

let labelFrame = CGRect(x: 0, y: 0, width: 100, height: 100)
let label = UILabel(frame: labelFrame)
label.backgroundColor = .lightGray
label.text = "Something that's pretty long"

label.baselineAdjustment = .alignCenters
label.adjustsFontSizeToFitWidth = true

label.numberOfLines = 2   // <<<<<< this is the only change
label.minimumScaleFactor = 0.1

let frame = CGRect(x: 0, y: 0, width: 300, height: 300)
let view = UIView(frame: frame)
view.backgroundColor = .white

view.addSubview(label)

PlaygroundPage.current.liveView = view

结果是:
ios - AdjustsFontSizeToFitWidth的异常行为-LMLPHP
怎么回事?这是虫子还是我做错了什么?

最佳答案

嗯,看起来这只是操场上的一个虫子。如果我加上这一行

label.lineBreakMode = .byTruncatingMiddle

一切如期而至。实际上,这些工作:
label.lineBreakMode = .byCharWrapping
label.lineBreakMode = .byClipping
label.lineBreakMode = .byTruncatingHead
label.lineBreakMode = .byTruncatingMiddle
label.lineBreakMode = .byWordWrapping

不起作用的(也是默认的)是
label.lineBreakMode = .byTruncatingTail

当我在一个真实的模拟器中尝试这个时,一切看起来都很好,所以我想我只是遇到了一个Playgrounds bug。

10-08 05:35