I'm trying to have the UILabel shrink so that words don't truncate to the next line. Not just text truncating at the end of the text area.
If I have a box that is 50x100, and I want to put in something like "American" in the box at 25.0pt, I end up getting:
50px
-------
|Ameri- |
|can |
|Beauty | 100px
| |
-------
The text shrinking doesn't seem to do anything during this situation, since it still fits in the UILabel frame. It works pretty well when the text is really long like "Willie Wonka's Chocolate Factory", but I don't want word truncation.
This is the ideal output in that scenario:
50px
--------
[American|
|Beauty | 100px
| |
| |
| |
--------
Any suggestions would be super appreicated!
Edit: SOLUTION
Here is what I ended up doing thanks to the suggestion in the answer below. It works great!
- (CGFloat) calculateFromUILabel:(UILabel *)label
{
NSString *stringToMeasure = label.text;
NSLog(@"FontSizeMeasurement.calculateFromUILabel() %@", stringToMeasure);
NSRange range = NSMakeRange(0, 1);
NSAttributedString *attributedString = label.attributedText;
NSDictionary *attributes = [attributedString attributesAtIndex:0 effectiveRange:&range];
NSMutableCharacterSet *characterSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
[characterSet addCharactersInString:@"-"];
NSArray *words = [stringToMeasure componentsSeparatedByCharactersInSet:characterSet];
CGSize maxSize = CGSizeZero;
NSMutableAttributedString *maxWidthString = nil;
for(int i = 0; i < words.count; i++) {
NSString *word = words[i];
CGSize wordSize = [word sizeWithAttributes:attributes];
if(wordSize.width > maxSize.width) {
maxSize = wordSize;
maxWidthString = [[NSMutableAttributedString alloc] initWithString:word attributes:attributes];
}
}
UIFont *font = [label.font copy];
while(maxSize.width > self.maxWidth) {
font = [font fontWithSize:(font.pointSize-0.1)];
[maxWidthString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, maxWidthString.length)];
maxSize = [maxWidthString size];
}
return font.pointSize;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…