Ignore Ascender and Descender when centering UILabel vertically?

Im uses AutoLayout to place some labels in the vertical center of the cell. The text is in all the caps, but the question UILabel, even when applied sizeToFit, leaves a place under the text, which is very similar to tails on letters such as lowercase y, p and q. Since Im centers vertically, this causes an offset and means that the text appears a few pixels higher than it should do.

One more question: can I reasonably adjust the font to its vertical center depending on whether it contains any characters that use a clip or a trigger?

For example, the string "abbaba" does not need a descender, while the string "oyyoyo" does not need an upstream. Lines in all caps also never need a trigger. If I vertically center "oyyoyoyo", it will seem too low.

enter image description here

+4
source share
3 answers

Thank you Abhinit for your reply.

I also searched for this, so I would like to place here the exact restrictions that you need to apply to align the texts to your liking.

This image from Wikipedia shows various sections of the font size.

enter image description here

, , , , x, .

, label "HELLO", viewAbove, viewBelow .

:

let font = label.font
let ascenderDelta = font.ascender - font.capHeight

LayoutHelper()
    .addViews([
        "label":label, "viewAbove":viewAbove, "viewBelow":viewBelow
    ])
    .withMetrics(["ascenderDelta":ascenderDelta])
    .addConstraints([

        // -- Here the constraints to align to cap height --
        "X:label.top == viewAbove.bottom - ascenderDelta",
        "X:label.baseline == viewBelow.top",

        ...other constraints...
    ])

: LayoutHelper, , .

"-":

, "" , , , descenders, ascenders, caps ..

, drawTextInRect ( , , , insets = {-ascenderDelta, 0, font.descender, 0}). / , . .

+3

"capHeight" "xHeight" UIFont, UILabel.

, , , . , setText UILabel , .

, CoreText - http://www.zsiegel.com/2012/10/23/Core-Text-Calculating-line-heights/

+4

UILabel :

- (void)drawRect:(CGRect)rect
{
   CGRect capCenteredRect = CGRectMake(rect.origin.x, (self.font.leading-self.font.capHeight)*0.5f, rect.size.width, rect.size.height);
   [super drawTextInRect:capCenteredRect];
}

, UILabel . descender, :

CGRectMake(rect.origin.x, (self.font.leading-self.font.xHeight)*0.5f+self.font.descender, rect.size.width, rect.size.height)
+2
source

All Articles