I have a UILabel
that I'm using inside a container view. I'm using AutoLayout entirely programmatically--no xib or storyboard. My UILabel
constraints (no height constraint set, large fixed width, top and left edges pinned, numberOfLines
= 0, bottom of superview pinned to bottom of label) work perfectly for normal (around 13 or 14 point) sized text, but at large (60 point) size text I started noticing large gaps of extra space above and below my character; in this case, the capital letter "S" that's an NSMutableAttributedString.
The only attributes
for this attributed string are the font name and a kerning value of 1.0. Below picture shows a magnified screenshot of my label from Pixie (white square shown is from that program) with my UILabel
's backgroundColor
in red:
After doing lots of research (Ignore Ascender and Descender when centering UILabel vertically?, iOS - Get the "real" height of a letter, Vertically center text in UILabel depending on actual visible letter height), it seemed the reason I was encountering this issue was because of the ascender and descender values for this font aren't getting used in this case (this is a capital "S," so it would seem I just need its capHeight
value). So, I decided to constrict my label height to this value, and did so by setting a height constraint equal to its capHeight
value after the "S" attributed text is set. Doing this produced the following image:
As you can see, the text is now clipped in the label. As a sort of hack, I figured I'd add some padding to counteract this, so multiplying my capHeight
value by 1.1 yielded the following image:
That's fine for some padding, but now there's 4 px of extra space at the top. Granted I'm zoomed in very far, but I'm not sure why I'm seeing this—I would think that since the height constraint is set to the height of this capHeight
value (which has some extra added for padding now) that the "S" would be vertically centered. I've tried calling setNeedsLayout
on the label, but that didn't do anything. These are the things I would love to know:
- Why is the
capHeight
value either not returning the correct value and/or setting the label's height constraint to this value is causing the text to get clipped? - Why do I need to add padding to the
capHeight
value? - Does anyone have any suggestions on how I can get this text vertically centered after I add padding and/or why it's not happening automatically? I saw this answer (https://stackoverflow.com/a/17376146/482557) but wasn't sure if that would apply here.
Thanks!