25

当我将文本添加到adjustsFontSizeToFitWidth设置为YES文本的标签时,文本不再垂直居中,并最终将文本剪辑到标签框架的底部。对于大量文本,它最终会从标签底部消失。

视图背景为蓝色,标签背景为白色

如果您添加较少的文本,会发生这种情况:

在此处输入图像描述

正如我所期望的那样剪裁了(即字体大小没有减小,文本在标签中垂直居中并剪裁在顶部和底部。

在此处输入图像描述

这是重现的代码:

- (void)loadView {
    [super loadView];

    self.view.backgroundColor = [UIColor blueColor];
    testLabel = [[UILabel alloc] init];
    testLabel.font = [UIFont boldSystemFontOfSize:172];
    testLabel.textColor = [UIColor blackColor];
    testLabel.adjustsFontSizeToFitWidth = YES;
    testLabel.numberOfLines = 1;
    testLabel.frame = CGRectMake(50, 50, 300, 100);
    testLabel.text = @"123";

    [self.view addSubview:testLabel];
}

这应该发生吗?以及如何让我的标签垂直居中而不考虑标签中的字符数。

4

2 回答 2

40

添加

testLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

到您的代码以垂直居中字体比例的文本。

于 2012-10-16T10:34:17.333 回答
-1

还想补充一点,adjustsFontSizeToFitWidth 不适用于属性文本,所以如果可以的话,将属性添加到标签而不是属性文本。这对我有用。

于 2015-08-21T14:19:36.913 回答