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 :
Do I have to do anything specific so it can be centered ?
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.
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 .
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With