Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make text in a UILabel shrink font size

If a UILabel contains too much text, how can I setup my label so that it shrinks font-sizes?

Here is how I am setting up my UILabel:

     descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 30, 130, 150)];     [descriptionLabel setFont:[Utils getSystemFontWithSize:14]];     [descriptionLabel setBackgroundColor:[UIColor clearColor]];     [descriptionLabel setTextColor:[UIColor whiteColor]];     descriptionLabel.numberOfLines = 1;     [self addSubview:descriptionLabel]; 
like image 559
Sheehan Alam Avatar asked Apr 21 '10 18:04

Sheehan Alam


People also ask

How do you change the font size on UILabel?

Change Font And Size Of UILabel In StoryboardSelect the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.

How do I change the size of labels in Xcode?

You can set the Minimum Font Scale or size in Storyboard/Xib when you set it up in IB under the Attributes inspector. I prefer scale, as it is better at fitting longer text on iPhone 4/5/iPod touches. If you set the size, you can get cut off earlier than with scale.


2 Answers

descriptionLabel.adjustsFontSizeToFitWidth = YES; descriptionLabel.minimumFontSize = 10.0; //adjust to preference obviously 

The following example is tested and verified on iPhone Simulator 3.1.2:

UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, 200, 30)];  descriptionLabel.font = [UIFont systemFontOfSize:14.0]; descriptionLabel.minimumFontSize = 10.0; descriptionLabel.adjustsFontSizeToFitWidth = YES; descriptionLabel.numberOfLines = 1; descriptionLabel.text = @"supercalifragilisticexpialidocious even thought he sound of it is something quite attrocious"; 
like image 168
prendio2 Avatar answered Oct 05 '22 17:10

prendio2


To resize the text in a multi-line UILabel, you can use this helper method (based on code from 11 Pixel Studios):

+ (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize {   // use font from provided label so we don't lose color, style, etc  UIFont *font = aLabel.font;   // start with maxSize and keep reducing until it doesn't clip  for(int i = maxSize; i >= minSize; i--) {   font = [font fontWithSize:i];   CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);    // This step checks how tall the label would be with the desired font.   CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];   if(labelSize.height <= aLabel.frame.size.height)    break;  }  // Set the UILabel's font to the newly adjusted font.  aLabel.font = font; } 
like image 33
Steve N Avatar answered Oct 05 '22 19:10

Steve N