Skip to content

Instantly share code, notes, and snippets.

@mkubenka
Forked from kevboh/NSString+KBAdditions.h
Last active March 16, 2016 11:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mkubenka/d886c534f7082db00540 to your computer and use it in GitHub Desktop.
Save mkubenka/d886c534f7082db00540 to your computer and use it in GitHub Desktop.
Add support for iOS7.
@interface NSString (KBAdditions)
- (CGFloat)fontSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size minimumScaleFactor:(CGFloat)minimumScaleFactor;
@end
#import "NSString+KBAdditions.h"
@implementation NSString (KBAdditions)
// Original code from http://stackoverflow.com/a/4383281/463892 & http://stackoverflow.com/a/18951386
- (CGFloat)fontSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size minimumScaleFactor:(CGFloat)minimumScaleFactor {
CGFloat minimumFontSize = [font pointSize] * minimumScaleFactor;
CGFloat fontSize = [font pointSize];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self
attributes:@{NSFontAttributeName: font}];
CGFloat height = [attributedText boundingRectWithSize:(CGSize){size.width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil].size.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];
attributedText = [[NSAttributedString alloc] initWithString:self
attributes:@{NSFontAttributeName: newFont}];
height = [attributedText boundingRectWithSize:(CGSize){size.width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil].size.height;
};
// Loop through words in string and resize to fit
for (NSString *word in [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]) {
CGFloat width = [word sizeWithAttributes:@{NSFontAttributeName:newFont}].width;
while (width > size.width && width != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName:font.fontName size:fontSize];
width = [word sizeWithAttributes:@{NSFontAttributeName:newFont}].width;
}
}
return fontSize;
}
@end
@interface UILabel (KBAdditions)
- (void)sizeToFitMultipleLines;
@end
#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 minimumScaleFactor:self.minimumScaleFactor];
self.font = [self.font fontWithSize:adjustedFontSize];
}
[self sizeToFit];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment