Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align labels with different font sizes, Swift

Tags:

ios

uilabel

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.

like image 391
SpaceX Avatar asked Jan 31 '26 05:01

SpaceX


1 Answers

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.

like image 125
Ole Begemann Avatar answered Feb 02 '26 17:02

Ole Begemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!