UILabel 从垂直中心开始

UILabel is starting from vertical center

您好,我从我的代码中添加了一个 UILabel。我已经设置为

let lb3 = UILabel(frame: CGRect(x: 0, y: 0, width: summaryView.frame.width - 20, height: 120))

        lb3.text = "This is body of the message. This is body of the message. This is body of the message. This is body of the message."
        lb3.textAlignment   = .left
        lb3.numberOfLines   = 10
        lb3.lineBreakMode   = .byWordWrapping
        lb3.backgroundColor = UIColor.cyan
        lb3.font = UIFont.systemFont(ofSize: 12, weight: .light)

根据片段,lb3 的总高度为 120 所以左上角在坐标 (0, 0) 和右下坐标 (x=width, 120) lb3 是从 (0, 60) 开始的,假设这个视图是从 (0, 0) 开始的,但我希望 lb3(0, 0) 本身开始,而不是从它的垂直中心开始。

我按以下方式添加了 lb3,因为这是我的视图层次结构

summaryView.addSubview(lb3)
v.addSubview(summaryView)
self.view.addSubview(v)

您所描述的根本不是 UILabel 的工作方式。他们的文本总是在标签的高度内垂直居中。您将标签设置得比其文本要求的要高得多,因此文本上方和下方有 space。

通常的替代方法是制作一个 UILabel,它设置自己的高度刚好足以包含它的文本(很容易做到);这样,文本从标签的左上角开始并完美地填充标签。

如前所述,UILabel 中的文本将始终垂直居中。解决您问题的一个很好的解决方法是:

var frame = CGRect(x: 0, y: 0, width: summaryView.frame.width - 20, height: 120)
let lb3 = UILabel(frame: frame)
lb3.text = "This is body of the message. This is body of the message. This is body of the message. This is body of the message."
lb3.textAlignment   = .left
lb3.numberOfLines   = 10
lb3.lineBreakMode   = .byWordWrapping
lb3.backgroundColor = UIColor.cyan
lb3.font = UIFont.systemFont(ofSize: 12, weight: .light)
lb3.sizeToFit()
frame.size.height = lb3.frame.size.height
lb3.frame = frame