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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…