我想知道当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
但是,当我将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
这是怎么回事?这是错误还是我做错了什么?
答案 0 :(得分:0)
嗯,看来这只是Playgrounds中的错误。如果我添加这一行
label.lineBreakMode = .byTruncatingMiddle
一切正常。实际上,任何这些工作:
label.lineBreakMode = .byCharWrapping
label.lineBreakMode = .byClipping
label.lineBreakMode = .byTruncatingHead
label.lineBreakMode = .byTruncatingMiddle
label.lineBreakMode = .byWordWrapping
不起作用(也是默认值)的是
label.lineBreakMode = .byTruncatingTail
当我在真实的模拟器中尝试此操作时,一切看起来都不错,所以我认为我刚遇到了Playgrounds错误。