Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipping of UILabel when adjustsFontSizeToFitWidth

Tags:

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.

like image 777
Magic Bullet Dave Avatar asked Oct 16 '12 10:10

Magic Bullet Dave


1 Answers

Add

testLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters; 

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

like image 111
Krumelur Avatar answered Oct 27 '22 10:10

Krumelur