SpaceX
SpaceX

Reputation: 2890

Vertically align labels with different font sizes, Swift

I would like to vertically align labels with different font sizes, so that they appear sitting on a common baseline.

In this case, I have three labels embedded inside a stackview as you can see in the below picture. Number 30 appears to be clearly offset from the baseline, whereas text 'In' and 'MINUTES' appears to be offset too, but not significant. How can I get all three to be sitting on the same baseline ?

enter image description here

I am creating the labels and stack view programatically as you can see below:

var timeStackView           : UIStackView!
var timeIndication          : UILabel!
var time                    : UILabel!
var unitsOrTimeZone         : UILabel!

timeStackView = UIStackView()
timeStackView.addArrangedSubview(timeIndication)
timeStackView.addArrangedSubview(time)
timeStackView.addArrangedSubview(unitsOrTimeZone)
timeStackView.alignment = .bottom      // bottom alignment
timeStackView.axis = .horizontal
timeStackView.distribution = .equalSpacing
timeStackView.spacing = 10.0

All the three labels are created in a similar way as shown below, but with different text:

timeIndication                      =   UILabel()
timeIndication.textAlignment        =   .center
timeIndication.text                 =   "In"
timeIndication.font                 =   timeIndication.font.withSize(14)
timeIndication.baselineAdjustment   = .alignBaselines // baselineAdjustment

I have tried timeStackView.alignment = .bottom and timeIndication.baselineAdjustment = .alignBaselines, but they don't seem to work.

Upvotes: 3

Views: 1724

Answers (2)

Ramis
Ramis

Reputation: 16519

In SwiftUI it is possible to achieve it by using: .lastTextBaseline

HStack(alignment: .lastTextBaseline) {
    Text("Hello")
        .font(.caption)
    Text("SwiftUI")
        .font(.subheadline)
}

Upvotes: 0

Ole Begemann
Ole Begemann

Reputation: 135540

I haven‘t tried it, but according to the UIStackView documentation, you should set the stack view‘s alignment to either .lastBaseline or .firstBaseline, depending on how you want multiline labels to be handled.

Upvotes: 8

Related Questions