Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text not vertically centered in UILabel

Tags:

ios

uilabel

swift

I've created a Label with the following code :

func setupValueLabel() {     valueLabel.numberOfLines = 1     valueLabel.font = UIFont(name: "Avenir-Black", size: 50)     valueLabel.adjustsFontSizeToFitWidth = true     valueLabel.clipsToBounds = true     valueLabel.backgroundColor = UIColor.greenColor()     valueLabel.textColor = valuesColor     valueLabel.textAlignment = NSTextAlignment.Center } 

I don't really understand why but the label is not vertically centered : Label not centered

Do I have to do anything specific so it can be centered ?

like image 766
Loadex Avatar asked Oct 30 '14 09:10

Loadex


People also ask

How do I center text vertically in react native?

To put a Text component vertically and horizontally center of View component in RN we have to use justifyContent: 'center' and alignItems: 'center' layout styles.

How do you align text on top of UILabel?

Set the UILabel number of lines equal to 0 . Embed the UILabel inside an UIView . Set the UIView constraints (top, right, left and bottom) to occupy the maximum space the UILabel should grow to. Then set the UILabel to top, right, and left of the UIView and also set a constraint to bottom with distance >= 0 .

How do I center a label in Xcode?

We want our label to be centrally constrained therefore while it's still selected, hold down the control button and drag a line to the left side of the screen then release it, a pop up menu will appear with this constraint options: Select Center Horizontally in Safe Area .


1 Answers

The problem is that font size is shrunk by adjustsFontSizeToFitWidth = true, but it does not adjust the lineHeight automatically. It remains to be for original font size that is 50.

By default, the text is aligned to its baseline. you can adjust it with baselineAdjustment property.

In your case, you should set it to UIBaselineAdjustment.alignCenters.

valueLabel.baselineAdjustment = .alignCenters 
like image 100
rintaro Avatar answered Sep 30 '22 11:09

rintaro