Autoshrink on a UILabel with multiple lines

I found this link http://beckyhansmeyer.com/2015/04/09/autoshrinking-text-in-a-multiline-uilabel/

The problem can be solved using the Interface Builder in 3 simple steps:

  1. Set “Autoshrink” to “Minimum font size.”
  2. Set the font to your largest desirable font size (20) and set Lines to, say, 10, which in my case was as many lines as would fit in the label at that font size.
  3. Then, change “Line Breaks” from “Word Wrap” to “Truncate Tail.”

Hope it helps!


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

Tags:

Ios

Uilabel

Ios5