Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoshrink on a UILabel with multiple lines

Tags:

ios

uilabel

ios5

Is it possible to use the autoshrink property in conjunction on multiple lines on a UILabel? for example, the large text size possible on 2 available lines.

like image 684
jfisk Avatar asked Jan 30 '12 05:01

jfisk


People also ask

What is UILabel?

A view that displays one or more lines of informational text.


1 Answers

I modified the accepted answer's code somewhat to make it a category on UILabel:

Header file:

#import <UIKit/UIKit.h> @interface UILabel (MultiLineAutoSize)     - (void)adjustFontSizeToFit; @end 

And the implementation file:

@implementation UILabel (MultiLineAutoSize)  - (void)adjustFontSizeToFit {     UIFont *font = self.font;     CGSize size = self.frame.size;          for (CGFloat maxSize = self.font.pointSize; maxSize >= self.minimumFontSize; maxSize -= 1.f)     {         font = [font fontWithSize:maxSize];         CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);         CGSize labelSize = [self.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];         if(labelSize.height <= size.height)         {             self.font = font;             [self setNeedsLayout];             break;         }     }     // set the font to the minimum size anyway     self.font = font;     [self setNeedsLayout]; }  @end 
like image 53
DaGaMs Avatar answered Sep 20 '22 18:09

DaGaMs