根据我的经验,您可以将 -[UILabel baselineAdjustment] 属性设置为 UIBaselineAdjustmentAlignCenters 以实现您所描述的效果 .
baselineAdjustment控制文本需要缩小以适应标签时如何调整文本基线 . @property(非原子)UIBaselineAdjustment baselineAdjustment
讨论如果adjustsFontSizeToFitWidth属性设置为YES,则此属性控制在需要调整字体大小的情况下文本基线的行为 . 此属性的默认值为UIBaselineAdjustmentAlignBaselines . 仅当numberOfLines属性设置为1时,此属性才有效 .
和
UIBaselineAdjustmentAlignCenters相对于其边界框的中心调整文本 .
EDIT: adding a full view-controller that demonstrates this:
@interface TSViewController : UIViewController
@end
@implementation TSViewController
- (void) addLabelWithFrame: (CGRect) f baselineAdjustment: (UIBaselineAdjustment) bla
{
UILabel* label = [[UILabel alloc] initWithFrame: f];
label.baselineAdjustment = bla;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont fontWithName: @"Courier" size: 200];
label.text = @"00";
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor lightGrayColor];
label.userInteractionEnabled = YES;
[self.view addSubview: label];
UIView* centerline = [[UIView alloc] initWithFrame: CGRectMake(f.origin.x, f.origin.y+(f.size.height/2.0), f.size.width, 1)];
centerline.backgroundColor = [UIColor redColor];
[self.view addSubview: centerline];
UITapGestureRecognizer* tgr = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)];
[label addGestureRecognizer: tgr];
}
- (void) viewDidLoad
{
[super viewDidLoad];
[self addLabelWithFrame: CGRectMake(0, 0, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignCenters];
[self addLabelWithFrame: CGRectMake(0, 220, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignBaselines];
}
- (void) onTap: (UITapGestureRecognizer*) tgr
{
UILabel* label = (UILabel*)tgr.view;
NSString* t = [label.text stringByAppendingString: @":00"];
label.text = t;
}
@end