Ignore Ascender and Descender when centering UILabel vertically?

前端 未结 3 1419
天命终不由人
天命终不由人 2021-01-12 17:08

I’m using AutoLayout to position some labels in the vertical centre of a cell. The text is in all-caps, but the UILabel in question, even when sizeToFit

3条回答
  •  难免孤独
    2021-01-12 18:02

    I had the same problem and solved it by subclassing UILabel and changing its draw method:

    - (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];
    }
    

    In my case I needed to center to caps because the vertical centering of the UILabel is always some pixels off. If you need to center vertically to lower case letters with descender you can change the rect to:

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

提交回复
热议问题