调整WhenFontSizeToFitWidth时剪切UILabel

时间:2012-10-16 10:30:58

标签: ios uilabel clipping

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

View background is blue, label background is white

如果你添加较少的文字会发生这种情况:

enter image description here

这是我所期望的剪辑(即字体大小没有缩小,文字在标签中垂直居中,并在顶部和底部剪裁。

enter image description here

以下是重现的代码:

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

这应该发生吗?如何将标签垂直居中,而不管标签中的字符数是多少。

2 个答案:

答案 0 :(得分:40)

添加

testLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

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

答案 1 :(得分:-1)

还要补充一点,adjustsFontSizeToFitWidth对属性文本的效果不佳,因此如果可以,请将属性添加到标签而不是属性文本。这对我有用。