Created
April 15, 2014 14:00
-
-
Save Leandros/10735084 to your computer and use it in GitHub Desktop.
Size Label
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (void)sizeLabel:(UILabel *)label toRect:(CGRect)labelRect { | |
label.frame = labelRect; | |
int maxFontSize = 18; | |
int minFontSize = 5; | |
NSInteger size = [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:maxFontSize withSize:label.frame.size]; | |
label.font = [UIFont fontWithName:label.font.fontName size:size]; | |
} | |
#pragma mark - | |
#pragma mark Helper Helper - | |
//=========================================================================================================================== | |
// Helper Helper. (Ohh the irony ...) | |
//=========================================================================================================================== | |
+ (NSInteger)binarySearchForFontSizeForLabel:(UILabel *)label withMinFontSize:(NSInteger)minFontSize withMaxFontSize:(NSInteger)maxFontSize withSize:(CGSize)size { | |
if (maxFontSize < minFontSize) { | |
return 0; | |
} | |
NSInteger fontSize = (minFontSize + maxFontSize) / 2; | |
UIFont *font = [UIFont fontWithName:label.font.fontName size:fontSize]; | |
CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT); | |
CGRect rect = [label.text boundingRectWithSize:constraintSize | |
options:NSStringDrawingUsesLineFragmentOrigin | |
attributes:@{NSFontAttributeName : font} | |
context:nil]; | |
CGSize labelSize = rect.size; | |
if (labelSize.height >= (size.height + 10) && labelSize.width >= (size.width + 10) && labelSize.height <= (size.height) && labelSize.width <= (size.width)) { | |
return fontSize; | |
} else if (labelSize.height > size.height || labelSize.width > size.width) { | |
return [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:fontSize - 1 withSize:size]; | |
} else { | |
return [self binarySearchForFontSizeForLabel:label withMinFontSize:fontSize + 1 withMaxFontSize:maxFontSize withSize:size]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment