如何在一行内垂直对齐两个 UILabel?

How to vertically align two UILabels within one line?

我试图将两个 UILabel 放在一行中:一个 UILable 在左侧,文本左对齐,一个 UILabel 在右侧,文本在右-对齐。请看上图。它们有不同的字体大小。

我使用了以下自动布局约束:

 let labelHorizontalConstrains = NSLayoutConstraint.constraints(
        withVisualFormat: "H:|-20-[nameLabel]-15-[birthDeathDateLabel]-20-|",
        metrics: nil,
        views: views)
    allConstraints += labelHorizontalConstrains

但结果显示它们不是垂直对齐的:左边UILabel低于右边UILabel。如何解决这个问题?

您需要添加一个 centerYAnchor 约束。

birthDeathDateLabel.centerYAnchor.constraint(equalTo: nameLabel.centerYAnchor).isActive = true

但是,如果您希望它与文本的底部对齐,您应该使用 UIStackView

let stackView = UIStackView(arrangedSubviews: [nameLabel, birthDeathDateLabel])
stackView.alignment = .firstBaseline
stackView.axis = .horizontal
// Add other stackview properties and constraints

您需要为右侧标签添加前导约束和高度约束。向左侧标签添加尾随和高度约束。然后指定一个等宽约束。同样在右侧标签上添加与左侧标签的距离和尾随约束,并为左侧标签添加前导约束您希望它与右侧标签的距离..在故事板上更容易。你也可以同样使用 fit ..我不记得实际的代码,但它可能会刷新你的记忆。如果我也添加了那种约束,我会在框架情节提要板上进行。