Vertically center text in UILabel depending on actual visible letter height

本小妞迷上赌 提交于 2019-11-29 12:19:50

I think you need to delve into core text to get the kind of glyph metrics needed to do this.

Then, rather than trying to move the text inside the UILabel, you could adjust the label's position so that the text ends up where you want it.

In the following example code, if _myLabel contains a character that currently has its baseline where you want the text centered then adjustLabel will center the visible glyph on that line.

In more realistic code you might calculate the entire bounds for the label based on the glyph bounds.

#import <CoreText/CoreText.h>

(And add the framework to your project. Then...)

- (void)adjustLabel
{
    UIFont *uiFont = _myLabel.font;

    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)(uiFont.fontName), uiFont.pointSize, NULL);

    UniChar ch = [_myLabel.text characterAtIndex:0];
    CGGlyph glyph;

    if (CTFontGetGlyphsForCharacters (ctFont, &ch, &glyph, 1)) {

        CGRect bounds = CTFontGetBoundingRectsForGlyphs (ctFont, kCTFontOrientationDefault, &glyph, nil, 1);
        CGFloat offset = bounds.origin.y + bounds.size.height/2.0;
        CGRect labelBounds = _myLabel.bounds;
        labelBounds.origin.y += offset;
        _myLabel.bounds = labelBounds;
    }
    CFRelease(ctFont);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!