【发布时间】:2020-01-31 04:32:12
【问题描述】:
我有一个 UILabel,它显示的文本基本上填满了屏幕。文本可以是一个字母,也可以是多个单词。
private lazy var myLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.baselineAdjustment = .alignCenters
label.numberOfLines = 0
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.1
let font = UIFont(name: "Arial Rounded MT Bold", size: 400)!
label.font = font
return label
}()
它是这样的约束:
self.myLabel.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(item: self.myLabel, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.myLabel.superview, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 20)
let trailingConstraint = NSLayoutConstraint(item: self.myLabel, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.myLabel.superview, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: -20)
let topConstraint = NSLayoutConstraint(item: self.myLabel, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.myLabel.superview, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 20)
let bottomConstraint = NSLayoutConstraint(item: self.myLabel, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.myLabel.superview, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: -20)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
标签的宽度正确显示。它动态调整宽度以匹配内容宽度。然而,在某些情况下,在高度中会有一些剪裁。最容易看到的是一个 W 字母。它在宽度上显示很好,但在高度上被剪裁了。
有没有办法让 UILabel 使用 Swift 5 调整字体以适应高度和宽度?
【问题讨论】:
-
可能会尝试将
topAnchor的常量减少到15 并检查并添加label.numberOfLines = 0 -
我以前做过,没有区别。
-
为什么你的底部约束值是
-20? -
您可能想在这里查看答案:stackoverflow.com/questions/9059631/…