I am trying to vertically center the text in a UILabel with a minimum line height.
For that I am setting the attributedText with a paragraphStyle (to set the minimumLineHeight), and a baselineOffset (to center the text vertically).
I am calculating the baseline offset by subtracting the font lineHeight to the minimum line height, but I can only get the expected behaviour if I use half that value - which doesn't make sense to me because all these units are in points.
One can easily and quickly reproduce this by creating a new Single View App project:
- Drag a Label to the storyboard's main scene and use autolayout to center it vertically and horizontally in the container
- Change the label's background color (so it's easy to see the extra space inside the label)
- Create an outlet for the label in ViewController.swift
- In viewDidLoad(), add the following code:
// Get font line height
let fontLineHeight = label.font.lineHeight
// Set paragraph minimum line height to have an extra 10 points
let minimumLineHeight: CGFloat = fontLineHeight + 10.0
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = minimumLineHeight
// Calculate baseline offset to move the text to the top of the label (which I'm expecting to be the extra 10 points)
let baselineOffset = minimumLineHeight - fontLineHeight
// Create and set the attributed text
let attributedText = NSAttributedString(string: "ÍÇ",
attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle,
NSAttributedString.Key.baselineOffset : baselineOffset])
label.attributedText = attributedText
This only works if I use baselineOffset / 2.
Can anyone help me understand why?
Cheers