26

When I add text to a label with the adjustsFontSizeToFitWidth set to YES the text is no longer centred vertically and eventually clips the text at the bottom of the label frame. For a large amount of text it will eventually disappear off the bottom of the label.

View background is blue, label background is white

This is what happens if you add less text:

enter image description here

This is clipped as I would expect it (i.e. the font size did not reduce, the text was vertically centred in the label and clipped on the top and bottom.

enter image description here

Here is the code to reproduce:

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

Should this happen? And how do I get my label to centre vertically irrespective of the number of characters in my label.

Magic Bullet Dave
  • 9,006
  • 10
  • 51
  • 81

2 Answers2

41

Add

testLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

to your code to vertical-center the text on font scale.

Krumelur
  • 31,081
  • 7
  • 77
  • 119
  • 1
    Brilliant, Krumelur! This worked perfectly, I had no idea about this property. I would be helpful for the adjustFontSizeToFitWidth property to mention this is the class reference. Thanks again. – Magic Bullet Dave Oct 16 '12 at 10:37
  • 1
    so many years of working with UILabel and I've never met this property)) – Tim Jul 08 '15 at 18:52
-1

Would also like add that adjustsFontSizeToFitWidth doesn't work too well with attributed text, so add your attributes to the label instead of the attributed text if you can. This worked for me.

AtomicBoolean
  • 1,070
  • 13
  • 19