public
Last active

Making UILabel's adjustsFontSizeToFitWidth and minimumFontSize play nice with multi-lined labels

  • Download Gist
NSString+KBAdditions.h
Objective-C
1 2 3
@interface NSString (KBAdditions)
- (CGFloat)fontSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size minimumFontSize:(CGFloat)minimumFontSize;
@end
NSString+KBAdditions.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#import "NSString+KBAdditions.h"
 
@implementation NSString (KBAdditions)
 
// Original code from http://stackoverflow.com/a/4383281/463892
- (CGFloat)fontSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size minimumFontSize:(CGFloat)minimumFontSize {
CGFloat fontSize = [font pointSize];
CGFloat height = [self sizeWithFont:font constrainedToSize:CGSizeMake(size.width,FLT_MAX) lineBreakMode:UILineBreakModeWordWrap].height;
UIFont *newFont = font;
//Reduce font size while too large, break if no height (empty string)
while (height > size.height && height != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName:font.fontName size:fontSize];
height = [self sizeWithFont:newFont constrainedToSize:CGSizeMake(size.width,FLT_MAX) lineBreakMode:UILineBreakModeWordWrap].height;
};
// Loop through words in string and resize to fit
for (NSString *word in [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]) {
CGFloat width = [word sizeWithFont:newFont].width;
while (width > size.width && width != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName:font.fontName size:fontSize];
width = [word sizeWithFont:newFont].width;
}
}
return fontSize;
}
 
@end
UILabel+KBAdditions.h
Objective-C
1 2 3
@interface UILabel (KBAdditions)
- (void)sizeToFitMultipleLines;
@end
UILabel+KBAdditions.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#import "UILabel+KBAdditions.h"
#import "NSString+KBAdditions.h"
 
@implementation UILabel (KBAdditions)
 
- (void)sizeToFitMultipleLines {
if (self.adjustsFontSizeToFitWidth) {
CGFloat adjustedFontSize = [self.text fontSizeWithFont:self.font constrainedToSize:self.frame.size minimumFontSize:self.minimumFontSize];
self.font = [self.font fontWithSize:adjustedFontSize];
}
[self sizeToFit];
}
 
@end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.